Main Concepts Flashcards
What is the smallest React example?
ReactDOM.render(
< h1 >Hello, world!< /h1 >,
document.getElementById(‘root’)
);
What is this an example of?
const element = < h1 >Hello, world!< /h1 >;
JSX.
What is React?
A JavaScript library for building user interfaces.
What is JSX?
A syntax extension to JavaScript.
How is JSX not like a template language?
Because it comes with the full power of JavaScript.
What does JSX produce?
React elements.
What does React embrace?
The fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.
What would React do instead of artificially separating technologies by putting markup and logic in separate files?
Separates concerns with loosely coupled units called “components” that contain both.
Does React require JSX?
No.
How do people find JSX useful?
As a visual aid when working with UI inside the JavaScript code.
What does JSX allow React to do?
To show more useful error and warning messages.
Declare a variable called name and then use it inside JSX by wrapping it in curly braces.
const name = 'Josh Perez'; const element = < h1 >Hello, { name }< /h1 >;
ReactDOM.render(
element,
document.getElementById(‘root’)
);
What can you put inside the curly braces in JSX?
Any valid JavaScript expression.
How can we make JSX more readable?
By splitting it over multiple lines.
What should you also do when splitting JSX over multiple lines and why?
Wrapping it in parentheses to avoid the pitfalls of automatic semicolon insertion.
What happens to JSX after compilation?
They become regular JavaScript function calls and evaluate to JavaScript objects.
What does JSX being compiled mean?
You can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions.
Show JSX being used inside an if statement.
function getGreeting(user) { if (user) { return < h1 >Hello, { formatName(user) }!< /h1 >; } return < h1 >Hello, Stranger.< /h1 >; }
How would you specify string literals as attributes?
By using quotes.
Show an example of using quotes to specify string literals as attributes.
const element = < div tabIndex=”0” >< /div >;
How would you embed a JavaScript expression in an attribute?
By using curly braces.
Show an example of using curly braces to embed a JavaScript expression in an attribute.
const element = < img src={ user.avatarUrl } >< /img >;
What should you note about using quotes (for string values) or curly braces (for expressions) in attributes.
You should use one or the other, not both at the same time.
What naming convention is used for JSX?
camelCase.
Show an example of JSX tags containing children.
const element = ( < div > < h1 >Hello!< /h1 > < h2 >Good to see you here.< /h2 > < /div > );
Is it safe to embed user input in JSX?
Yes.
Show an example of embedding user input in JSX.
const title = response.potentiallyMaliciousInput; // This is safe: const element = < h1 >{ title }< /h1 >;
What does ReactDOM do by default with values embedded in JSX?
Escapes them before rendering them.
What does React DOM escaping any values embedded in JSX before rendering them ensure?
You can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered.
What does React DOM escaping any values embedded in JSX before rendering help prevent?
XSS (cross-site-scripting) attacks.
What does Babel compile JSX down to?
React.createElement() calls.
What would this code look like when run through Babel?
const element = ( < h1 className="greeting" > Hello, world! < /h1 > );
const element = React.createElement( 'h1', { className: 'greeting' }, 'Hello, world!' );
What does React.createElement() perform.
A few checks to help you write bug-free code but essentially it creates an object like this:
// Note: this structure is simplified const element = { type: 'h1', props: { className: 'greeting', children: 'Hello, world!' } };
What are the objects created from React.createElement() called?
React elements.
What can you think of React elements as?
Descriptions of what you want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.
What does a element describe?
What you want to see on the screen.
How do DOM elements differ from React elements?
They’re plain objects, and are cheap to create.
What takes care of updating the DOM to match the React elements.
React DOM.
What are elements?
They’re what components are made up of.
What is a “root” DOM node?
A node where everything inside it will be managed by React DOM.
How many root DOM nodes does a React application have?
Usually one, unless you are integrating React into an existing app, then you may have as many isolated root DOM nodes as you like.
Ho do you render a React element into a root DOM node?
Pass both to ReactDOM.render().
Show an example of rendering a React element into a root DOM node?
const element = < h1 >Hello, world< /h1 >; ReactDOM.render(element, document.getElementById('root'));
What does it mean that React elements are immutable?
Once you create an element, you can’t change its children or attributes.
Whats a good way of thinking about an element?
As a single frame in a movie: it represents the UI at a certain point in time.
How many times do React apps usually call ReactDOM.render()
Once.
What does React DOM do after it compares the element and its children to the previous one?
Only applies the DOM updates necessary to bring the DOM to the desired state.
How can you verify that React DOM only applies the DOM updates necessary to bring the DOM to the desired state?
by inspecting the last example with the browser tools.
What do components let you do?
Split the UI into independent, reusable pieces, and think about each piece in isolation.
Conceptually, what are components like?
JavaScript functions.
What do components accepts and return?
They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
What is the simplest way to define a component?
By writing a JavaScript function.
Write a simple component as a JavaScript function.
function Welcome(props) { return < h1 >Hello, { props.name }< /h1 >; }
Why is this function a valid React component?
function Welcome(props) { return < h1 >Hello, { props.name }< /h1 >; }
Because it accepts a single “props” (which stands for properties) object argument with data and returns a React element.
What do we call this type of component?
function Welcome(props) { return < h1 >Hello, { props.name }< /h1 >; }
A “function component” because they are literally JavaScript functions.
How would you use an ES6 class to define a function component?
class Welcome extends React.Component { render() { return < h1 >Hello, { this.props.name }< /h1 >; } }
Show an example of an element that can also represent user-defined components.
const element = < Welcome name=”Sara” / >;
What does React do when it sees an element representing a user-defined component?
It passes JSX attributes to this component as a single object called “props”.
How should you always start a components name?
With a capital letter.
Why should you always start a components name with a capital letter?
Because React treats components starting with lowercase letters as DOM tags. For example, < div / > represents an HTML div tag, but < Welcome / > represents a component and requires Welcome to be in scope.
What does components referring to other components in their output allow?
To use the same component abstraction for any level of detail.
In React how is a button, a form, a dialog, a screen, commonly expressed as?
Components.
Typically, what do new React apps have at the very top?
A single App component. However, if you integrate React into an existing app, you might start bottom-up with a small component like Button and gradually work your way to the top of the view hierarchy.
When is it a good idea to have reusable components?
If a part of your UI is used several times, or is complex enough on its own.
What should you never do whether you declare a component as a function or a class?
Modify its own props.
What is Reacts single strict rule?
All React components must act like pure functions with respect to their props.
What does State allow in React components?
To change their output over time in response to user actions, network responses, and anything else, without violating Reacts single strict rule.
How is state different to props?
It’s private and fully controlled by the component.
How can you convert a function component to a class?
Create an ES6 class, with the same name, that extends React.Component.
Add a single empty method to it called render().
Move the body of the function into the render() method.
Replace props with this.props in the render() body.
Delete the remaining empty function declaration.
When does the render method get called?
(at the start) and each time an update happens.
What are some examples of additional features converting a …. function to a class give us access to?
Using local state and lifecycle methods.
How could you move ‘date’ from props to state?
Replace this.props.date with this.state.date in the render() method.
Add a class constructor that assigns the initial this.state
Note how we pass props to the base constructor.
Class components should always call the base constructor with props.
Remove the date prop from the element.
What do you do in applications when components are destroyed?
Free up resources they take.
What is it called when something is rendered to the DOM for the first time?
Mounting.
What is it called when you want to clear something whenever the DOM produced by ……… is removed?
Unmounting.
How would you mount and unmount some code?
By declaring special methods on the component class called componentDidMount() and componentWillUnmount()
What are componentDidMount() and componentWillUnmount() examples of?
Lifecycle methods.
When does the componentDidMount() method run?
After the component output has been rendered to the DOM.
What should you not do with state?
Modify it directly.
How should you modify state?
By using setState()
Where do you put this.state?
In the constructor.
What might React do in regards to setState() calls for performance?
Batch multiple calls into a single update.
Why shouldn’t you rely on this.props and this.state values for calculating the next state?
Because they may be updated asynchronously.
Because this.props and this.state may be updated asynchronously, what’s a better way of calculating state?
Use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
How would you convert this code to make sure counter is the correct value?
this.setState( {
counter: this.state.counter + this.props.increment,
} );
this.setState((state, props) => ( {
counter: state.counter + props.increment
} ));
How would you convert this arrow function to a regular function?
this.setState((state, props) => ( {
counter: state.counter + props.increment
} ));
this.setState(function(state, props) { return { counter: state.counter + props.increment }; } );
What happens when you call setState()
React merges the object you provide into the current state.
What happens when your state contain several independent variables, and you update them independently with separate setState() calls?
The merging is shallow, so this.setState({x}) leaves this.state.y intact, but completely replaces this.state.x
How can a parent or child component know if a certain component is stateful or stateless?
They can’t and they shouldn’t care whether it is defined as a function or a class.
Why is state often called local or encapsulated?
It’s not accessible to any component other than the one that owns and sets it.
How can a component pass its sate down to its child components?
As props.
< FormattedDate date={ this.state.date } / >
How would The FormattedDate component (that receives the date in its props) know where it came from?
It wouldn’t know whether it came from the Clock’s state, from the Clock’s props, or was typed by hand.
What does it mean when something has a “top-down” or “unidirectional” data flow?
Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.
If you imagine a component tree as a waterfall of props, continue the analogy for state.
Each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.
In React apps, what is it considered when a component is stateful or stateless?
An implementation detail of the component that may change over time. You can use stateless components inside stateful components, and vice versa.
What are some syntactic differences when handling events with React elements vs handling events on DOM elements?
React events are named using camelCase, rather than lowercase.
With JSX you pass a function as the event handler, rather than a string.
Convert this to a React implementation.
< button onclick=”activateLasers()” >
Activate Lasers
< /button >
< button onClick={ activateLasers } >
Activate Lasers
< /button >
How would you prevent default behavior in React?
You can’t return false. You must call preventDefault explicitly.
with plain HTML, to prevent the default link behavior of opening a new page, you can write.
< a href=”#” onclick=”console.log(‘The link was clicked.’); return false” >
Click me
< /a >
How would you do this in React?
function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); }
return ( < a href="#" onClick={handleClick} > Click me < /a > ); }
What is ‘e’ mean in this code?
function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); }
return ( < a href="#" onClick={handleClick} > Click me < /a > ); }
It’s a synthetic event. React defines these synthetic events according to the W3C spec, so you don’t need to worry about cross-browser compatibility.
When using React, you generally don’t need to call addEventListener to add listeners to a DOM element after it is created. What would you usually do instead?
Just provide a listener when the element is initially rendered.
When you define a component using an ES6 class, what is a common pattern in regards to an event handler?
For an event handler to be a method on the class.
Why do you have to be careful about the meaning of this in JSX callbacks?
Because in JavaScript, class methods are not bound by default.
What happens if you forget to bind this.handleClick and pass it to onClick?
this will be undefined when the function is actually called. This is not React-specific behavior; it is a part of how functions work in JavaScript.
Generally, what should you do if you refer to a method without () after it, such as onClick={ this.handleClick }?
You should bind that method.
If calling bind annoys you, what can you do to get around this?
If you are using the experimental public class fields syntax, you can use class fields to correctly bind callbacks. If you aren’t using class fields syntax, you can use an arrow function in the callback.
Give an example of using the experimental public class fields syntax you can use on class fields to correctly bind callbacks.
class LoggingButton extends React.Component { // This syntax ensures `this` is bound within handleClick. // Warning: this is *experimental* syntax. handleClick = () => { console.log('this is:', this); }
render() { return ( < button onClick={ this.handleClick } > Click me < /button > ); } }
If you aren’t using class fields syntax, give an example of using an arrow function in the callback to correctly bind callbacks.
class LoggingButton extends React.Component { handleClick() { console.log('this is:', this); }
render() { // This syntax ensures `this` is bound within handleClick return ( < button onClick={ (e) => this.handleClick(e) } > Click me < /button > ); } }
What’s the problem with this code?
class LoggingButton extends React.Component { handleClick() { console.log('this is:', this); }
render() { // This syntax ensures `this` is bound within handleClick return ( < button onClick={ (e) => this.handleClick(e) } > Click me < /button > ); } }
A different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. It’s generally recommend to bind in the constructor or use the class fields syntax, to avoid this sort of performance problem.
What is it common to do inside of a loop?
To want to pass an extra parameter to an event handler.
If id is the row ID, show code to delete the row.
< button onClick={(e) => this.deleteRow(id, e)} >Delete Row< /button >
or
< button onClick={this.deleteRow.bind(this, id)} >Delete Row< /button >
What do these lines of code use to get the same job done?
< button onClick={ (e) => this.deleteRow(id, e) } >Delete Row< /button >
< button onClick={ this.deleteRow.bind(this, id) } >Delete Row< /button >
Use an arrow function and Function.prototype.bind respectively.
How would you use conditional rendering in React?
The same way as you would in JavaScript. Use JavaScript operators like ‘if’ or the ‘conditional operator’ to create elements representing the current state, and let React update the UI to match them.
Using these two components, create a Greeting component that displays either of these components depending on whether a user is logged in.
function UserGreeting(props) { return < h1 >Welcome back!< /h1 >; }
function GuestGreeting(props) { return < h1 >Please sign up.< /h1 >; }
function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return < UserGreeting / >; } return < GuestGreeting / >; }
ReactDOM.render(
,
document.getElementById(‘root’)
);
What can using variables to store elements help with?
Conditionally rendering a part of the component while the rest of the output doesn’t change.
You may embed any expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical & & operator. What can this be handy for?
Conditionally including an element.
in JavaScript, what does ‘true & & expression’ and ‘false & & expression’ always evaluates to?
expression and false respectively.
What happens if the condition is true and false?
If it’s true the element right after & & will appear in the output. If it is false, React will ignore and skip it.
Show a simple example of rendering elements inline is to use the JavaScript conditional operator.
condition ? true : false
Use the JavaScript conditional operator to conditionally render a small block of text.
render() { const isLoggedIn = this.state.isLoggedIn; return ( < div > The user is < b >{ isLoggedIn ? 'currently' : 'not' }< /b > logged in. < /div > ); }
What is something you should consider whenever conditions become too complex?
Extracting a component.
How would you make a component hide itself even though it was rendered by another component?
Return null instead of its render output.
Show an example of how you would make a component hide itself even though it was rendered by another component?
function WarningBanner(props) { if (!props.warn) { return null; } ....... Here, If the value of the prop is false, then the component does not render.
What is something to note when returning null from a component’s render method?
It doesn’t affect the firing of the component’s lifecycle methods. For instance componentDidUpdate will still be called.
Use the map() function to take an array of numbers and double their values. Then assign the new array returned by map() to the variable doubled and log it.
const numbers = [ 1, 2, 3, 4, 5 ]; const doubled = numbers.map((number) => number * 2); console.log(doubled);
In React, how would you transform arrays into lists of elements.
By using .map()
Show how you would render a list of items in an array not in a component.
const numbers = [ 1, 2, 3, 4, 5 ]; const listItems = numbers.map((number) => < li >{ number }< /li > );
ReactDOM.render(
< ul >{ listItems }< /ul >,
document.getElementById(‘root’)
);
Show how you would render a list of items in an array in a component without a key.
function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => < li >{ number }< /li > ); return ( < ul >{ listItems }< /ul > ); }
const numbers = [ 1, 2, 3, 4, 5 ]; ReactDOM.render( < NumberList numbers={numbers} / >, document.getElementById('root') );
What is a key?
A special string attribute you need to include when creating lists of elements.
Show how you would render a list of items in an array in a component with a key.
function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => < li key={ number.toString() } > {number} < /li > ); return ( < ul >{ listItems }< /ul > ); }
const numbers = [ 1, 2, 3, 4, 5 ]; ReactDOM.render( < NumberList numbers={ numbers } / >, document.getElementById('root') );
What do keys do?
Help React identify which items have changed, are added, or are removed.
Where should keys be given to, and why?
Elements inside the array to give the elements a stable identity.
What’s the best way to pick a key?
Use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:
Show an example of picking a key.
const todoItems = todos.map((todo) => < li key={ todo.id } > { todo.text } < /li > );
How can you name a key when you don’t have stable IDs for rendered items.
As a key as a last resort, you can use the item index .
Show an example of naming a key via its item index.
const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
< li key={ index } >
{ todo.text }
< /li >
);
When is it not recommended to use indexes for keys?
When the order of items may change.
Why is it bad to use indexes for keys where the order of the items may change?
Because they can negatively impact performance and may cause issues with component state.
What happens if you choose not to assign an explicit key to list items?
React will default to using indexes as keys.
Keys only make sense in the context of the surrounding array. Give an example expanding on this.
If you extract a ListItem component, you should keep the key on the < ListItem / > elements in the array rather than on the < li > element in the ListItem itself.
Convert this to correct key usage.
function ListItem(props) { const value = props.value; return ( // Wrong! There is no need to specify the key here: < li key={ value.toString() } > { value } < /li > ); }
function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => // Wrong! The key should have been specified here: < ListItem value={ number } / > ); return ( < ul > { listItems } < /ul > ); }
const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( < NumberList numbers={numbers} / >, document.getElementById('root') );
function ListItem(props) { // Correct! There is no need to specify the key here: return < li >{ props.value }< /li >; }
function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => // Correct! Key should be specified inside the array. < ListItem key={ number.toString() } value={ number } / >
); return ( < ul > { listItems } < /ul > ); }
const numbers = [ 1, 2, 3, 4, 5 ]; ReactDOM.render( < NumberList numbers={ numbers } / >, document.getElementById('root') );
What’s a good rule of thumb in regards to keys?
That elements inside the map() call need keys.
What should be noted regarding uniqueness of keys used within arrays?
They should be unique among their siblings. However they don’t need to be globally unique. We can use the same keys when we produce two different arrays.
Keys serve as a hint to React but they don’t get passed to your components. What should you do if you need the same value in your component?
Pass it explicitly as a prop with a different name.
Show an example of passing a key explicitly as a prop with a different name to a component.??
const content = posts.map((post) => < Post key={ post.id } id={ post.id } title={ post.title } / > );
With the example above, the Post component can read props.id, but not props.key.
JSX allows embedding any expression in curly braces. Convert this code so we could inline the map() result.
function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => < ListItem key={ number.toString() } value={ number } / >
); return ( < ul > { listItems } < /ul > ); }
function NumberList(props) { const numbers = props.numbers; return ( < ul > { numbers.map((number) => < ListItem key={ number.toString() } value={ number } / >
)} < /ul > ); }
Whats something to keep in mind if the map() body is too nested?
It might be a good time to extract a component.
What is extracting components?
Splitting components into smaller components.
Why do HTML form elements work a little bit differently from other DOM elements in React?
Because form elements naturally keep some internal state.
Create an HTML form that accepts a single name.
< form > < label > Name: < input type="text" name="name" / > < /label > < input type="submit" value="Submit" / > < /form >
What behavior will this form have?
< form > < label > Name: < input type="text" name="name" / > < /label > < input type="submit" value="Submit" / > < /form >
Default HTML form behavior.
What is the default HTML form behavior?
Browsing to a new page when the user submits the form.
What is the default behavior of React with regards to forms??
The same as HTML.
In most cases with forms in React, what is the desired process?
To have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form.
What’s the standard way to achieve having a JavaScript function handle the submission of the form and having access to the data that the user entered into the form?
With a technique called “controlled components”.
In HTML, how is state maintained in form elements such as < input >, < textarea >, and < select >
They typically maintain their own state.
In HTML, how is state updated in form elements such as < input >, < textarea >, and < select >
Updates are based on user input.
In React, where is mutable state is typically kept?
In the state property of components, and only updated with setState()
In regards to controlled components, how should React state be thought of?
As the “single source of truth”.
What does the React component that renders a form also control?
What happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.
Write an example of logging a name from a form when it is submitted as a controlled component.
class NameForm extends React.Component { constructor(props) { super(props); this.state = { value: '' };
this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); }
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
alert(‘A name was submitted: ‘ + this.state.value);
event.preventDefault();
}
render() { return ( < form onSubmit={ this.handleSubmit } > < label > Name: < input type="text" value={ this.state.value } onChange={ this.handleChange } / > < /label > < input type="submit" value="Submit" / > < /form > ); } }
How is React the source of truth in this code?
class NameForm extends React.Component { constructor(props) { super(props); this.state = { value: '' };
this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); }
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
alert(‘A name was submitted: ‘ + this.state.value);
event.preventDefault();
}
render() { return ( < form onSubmit={ this.handleSubmit } > < label > Name: < input type="text" value={ this.state.value } onChange={ this.handleChange } / > < /label > < input type="submit" value="Submit" / > < /form > ); } }
Since the value attribute is set on our form element, the displayed value will always be this.state.value, making the React state the source of truth.
How will the displayed value be updated with this code?
class NameForm extends React.Component { constructor(props) { super(props); this.state = { value: '' };
this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); }
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
alert(‘A name was submitted: ‘ + this.state.value);
event.preventDefault();
}
render() { return ( < form onSubmit={ this.handleSubmit } > < label > Name: < input type="text" value={ this.state.value } onChange={ this.handleChange } / > < /label > < input type="submit" value="Submit" / > < /form > ); } }
Since handleChange runs on every keystroke to update the React state, the displayed value will update as the user types.
In a controlled component, what will every state mutation have?
An associated handler function.
With a controlled component, why would you want every state mutation to have an associated handler function.?
To make it straightforward to modify or validate user input.
Write a handleChange to make sure that names are written with all uppercase letters.
handleChange(event) {
this.setState( { value: event.target.value.toUpperCase() } );
}
In HTML, what does a < textarea > element define?
Its text by its children.
How does < textarea > differ in React compared to HTML?
It uses a value attribute instead. This way, a form using a < textarea > can be written very similarly to a form that uses a single-line input.
Show a simple example of writing a < textarea > in React with an attribute.
< form onSubmit={ this.handleSubmit } >
< label >
Essay:
< textarea value={ this.state.value } onChange={ this.handleChange } / >
< /label >
< input type=”submit” value=”Submit” / >
< /form >
NOTE: this.state.value would be initialized in the constructor, so that the text area starts off with some text in it.
In HTML, what does < select > do?
Create a drop-down list.
Show a simple example of how you would create a drop-down list of flavors in HTML.
< select >
< option value=”grapefruit” >Grapefruit< /option >
< option value=”lime” >Lime< /option >
< option selected value=”coconut” >Coconut< /option >
< option value=”mango” >Mango< /option >
< /select >
Here the Coconut option is initially selected, because of the selected attribute. How would React achieve this?
< select >
< option value=”grapefruit” >Grapefruit< /option >
< option value=”lime” >Lime< /option >
< option selected value=”coconut” >Coconut< /option >
< option value=”mango” >Mango< /option >
< /select >
It uses a value attribute on the root select tag.
Why is it more convenient for React to use a value attribute on the root select tag instead of the selected attribute?
Because you only need to update it in one place.
Show a simple example of a React form that uses a selected attribute.
< form onSubmit={ this.handleSubmit } >
< label >
Pick your favorite flavor:
< select value={ this.state.value } onChange={ this.handleChange } >
< option value=”grapefruit” >Grapefruit< /option >
< option value=”lime” >Lime< /option >
< option value=”coconut” >Coconut< /option >
< option value=”mango” >Mango< /option >
< /select >
< /label >
< input type=”submit” value=”Submit” / >
< /form >
What is something to note with < input type=”text” >, < textarea >, and < select > in regards to React?
They all work very similarly - they all accept a value attribute that you can use to implement a controlled component.
What is something to nor in regards to the value attribute in a React form?
That you can pass an array into the value attribute, allowing you to select multiple options in a select tag.
Show a simple example of using an array in the value attribute of a React form.
< select multiple={ true } value={ [‘B’, ‘C’] } >
In HTML, what does an < input type=”file” > allow you to do?
Lets the user choose one or more files from their device storage to be uploaded to a server or manipulated by JavaScript via the File API.
What is the value of this input in HTML?
< input type=”file” / >
Read-only, meaning it’s an uncontrolled component in React.
What can you do if you need to handle multiple controlled input elements?
Add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
Show an example of adding a name attribute to each element and letting the handler function choose what to do based on the value of event.target.name.
class Reservation extends React.Component { constructor(props) { super(props); this.state = { isGoing: true, numberOfGuests: 2 };
this.handleInputChange = this.handleInputChange.bind(this); }
handleInputChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name;
this.setState({ [name]: value }); }
render() { return ( < form > < label > Is going: < input name="isGoing" type="checkbox" checked={ this.state.isGoing } onChange={ this.handleInputChange } / > < /label > < br / > < label > Number of guests: < input name="numberOfGuests" type="number" value={this.state.numberOfGuests} onChange={this.handleInputChange} / > < /label > < /form > ); } }
Note how we used the ES6 computed property name syntax to update the state key corresponding to the given input name:
this.setState({
[name]: value
});
What is this ES6’s, ES5 equivalent?
this.setState({
[name]: value
});
var partialState = {}; partialState[name] = value; this.setState(partialState);
Also, since setState() automatically merges a partial state into the current state, we only needed to call it with the changed parts.
What does specifying the value prop on a controlled component do?
Prevents the user from changing the input unless you desire so.
If you’ve specified a value but the input is still editable, what might you have done?
Accidentally set value to undefined or null.
The following code demonstrates this. (The input is locked at first but becomes editable after a short delay.)
ReactDOM.render(< input value=”hi” / >, mountNode);
setTimeout(function() {
ReactDOM.render(< input value={ null } / >, mountNode);
}, 1000);
Why is it sometimes tedious to use controlled components?
Because you need to write an event handler for every way your data can change and pipe all of the input state through a React component.
When can using controlled components be particularly tedious?
When you are converting a preexisting codebase to React, or integrating a React application with a non-React library.
What is an alternative to using controlled components for implementing input forms?
Uncontrolled components.
If you’re looking for a complete solution for implementing forms including validation, keeping track of the visited fields, and handling form submission, what is a good choice.
Formik.
What principals is Formik built on?
The same principles of controlled components and managing state.
What is recommended when several components need to reflect the same changing data?
Lifting the shared state up to their closest common ancestor.
LIFTING STATE UP
Write notes.
Is using composition or inheritance recommended to reuse code between components?
Composition as React has a powerful composition model.
What is recommended when some components don’t know their children ahead of time (especially common for components like Sidebar or Dialog that represent generic “boxes”)?
That the components use the special children prop to pass children elements directly into their output.
Show an example of components using the special children prop to pass children elements directly into their output.
function FancyBorder(props) { return ( < div className={ 'FancyBorder FancyBorder-' + props.color } > { props.children } < /div > ); }
What does using the special children prop to pass children elements directly into their output allow?
Other components to pass arbitrary children to them by nesting the JSX.
Show an example of other components passing arbitrary children to them by nesting the JSX.
function WelcomeDialog() { return ( < FancyBorder color="blue" > < h1 className="Dialog-title" > Welcome < /h1 > < p className="Dialog-message" > Thank you for visiting our spacecraft! < /p > < /FancyBorder > ); }
What is happening with the < FancyBorder > tag?
function WelcomeDialog() { return ( < FancyBorder color="blue" > < h1 className="Dialog-title" > Welcome < /h1 > < p className="Dialog-message" > Thank you for visiting our spacecraft! < /p > < /FancyBorder > ); }
Anything inside the < FancyBorder > JSX tag gets passed into the FancyBorder component as a children prop. Since FancyBorder renders {props.children} inside a < div >, the passed elements appear in the final output.
Although less common, what should you do if you need multiple “holes” in a component?
Come up with your own convention instead of using children.
Show an example of needing multiple “holes” in a component.
function SplitPane(props) { return ( < div className="SplitPane" > < div className="SplitPane-left" > { props.left } < /div > < div className="SplitPane-right" > { props.right } < /div > < /div > ); }
function App() { return ( < SplitPane left={ < Contacts / > } right={ < Chat / > } / > ); }
What’s noteworthy about React elements like and
function SplitPane(props) { return ( < div className="SplitPane" > < div className="SplitPane-left" > {props.left} < /div > < div className="SplitPane-right" > {props.right} < /div > < /div > ); }
function App() { return ( < SplitPane left={ < Contacts / > } right={ < Chat / > } / > ); }
They are just objects, so you can pass them as props like any other data. This approach may remind you of “slots” in other libraries but there are no limitations on what you can pass as props in React.
Show an example of how sometimes we can think about components as being “special cases” of other components.
We might say that a WelcomeDialog is a special case of Dialog.
In React, how else are “special cases” components achieved??
By composition, where a more “specific” component renders a more “generic” one and configures it with props.
Show an example of composition in React.
function Dialog(props) { return ( < FancyBorder color="blue" > < h1 className="Dialog-title" > { props.title } < /h1 > < p className="Dialog-message" > { props.message } < /p > < /FancyBorder > ); }
function WelcomeDialog() { return ( < Dialog title="Welcome" message="Thank you for visiting our spacecraft!" / >
);
}
Show an example of composition working with components defined as classes.
function Dialog(props) { return ( < FancyBorder color="blue" > < h1 className="Dialog-title" > { props.title } < /h1 > < p className="Dialog-message" > { props.message } < /p > { props.children } < /FancyBorder > ); }
class SignUpDialog extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleSignUp = this.handleSignUp.bind(this); this.state = { login: '' }; }
render() {
return (
< Dialog title=”Mars Exploration Program”
message=”How should we refer to you?” >
< input value={ this.state.login }
onChange={ this.handleChange } / >
< button onClick={ this.handleSignUp } > Sign Me Up! < /button > < /Dialog > ); }
handleChange(e) {
this.setState({ login: e.target.value });
}
handleSignUp() {
alert(Welcome aboard, ${ this.state.login }!
);
}
}
Is there a time where creating component inheritance hierarchies is better than composition.
No.
What does props and composition give you?
All the flexibility you need to customize a component’s look and behavior in an explicit and safe way.
What is good to remember in regards to what components may accept?
They may accept arbitrary props, including primitive values, React elements, or functions.
What should you do if you want to reuse non-UI functionality between components?
Extract it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.
What’s a good process when thinking in React.
Start With A Mock Break The UI Into A Component Hierarchy Build A Static Version in React Identify The Minimal (but complete) Representation Of UI State Identify Where Your State Should Live Add Inverse Data Flow
Whats an example of a JSON mock?
[
{ category: “Sporting Goods”, price: “$49.99”, stocked: true, name: “Football” },
{ category: “Sporting Goods”, price: “$9.99”, stocked: true, name: “Baseball” },
{ category: “Sporting Goods”, price: “$29.99”, stocked: false, name: “Basketball” },
{ category: “Electronics”, price: “$99.99”, stocked: true, name: “iPod Touch” },
{ category: “Electronics”, price: “$399.99”, stocked: false, name: “iPhone 5” },
{ category: “Electronics”, price: “$199.99”, stocked: true, name: “Nexus 7” }
];
How would you break The UI Into A Component Hierarchy?
The first thing you’ll want to do is to draw boxes around every component (and subcomponent) in the mock and give them all names. If you’re working with a designer, they may have already done this, so go talk to them! Their Photoshop layer names may end up being the names of your React components!
But how do you know what should be its own component?
Use the same techniques for deciding if you should create a new function or object. One such technique is the single responsibility principle.
What is the single responsibility principle?
A component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents.
What is something you will find if you’re often displaying a JSON data model to a user if your model was built correctly?
your UI (and therefore your component structure) will map nicely.
Why would your UI (and therefore your component structure) map nicely if your model was built correctly?
UI and data models tend to adhere to the same information architecture. Separate your UI into components, where each component matches one piece of your data model.
split last question?
asdf
Import Image.
FilterableProductTable (orange): contains the entirety of the example
SearchBar (blue): receives all user input
ProductTable (green): displays and filters the data collection based on user input
ProductCategoryRow (turquoise): displays a heading for each category
ProductRow (red): displays a row for each product
Import Image. 2
asdf
Import Image. 3
asdf
Import Image. 4
sadf
How would you arrange the identified components in the mock into a hierarchy?
NOTE: Components that appear within another component in the mock should appear as a child in the hierarchy.
FilterableProductTable
- SearchBar - ProductTable - -ProductCategoryRow - -ProductRow
After you have your component hierarchy, what’s the best way to implement your app.
To build a version that takes your data model and renders the UI but has no interactivity.
Why is it best to build a version of your app that takes your data model and renders the UI but has no interactivity.
Because building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing.
What will you want when you build a static version of your app that renders your data model?
Build components that reuse other components and pass data using props.
What’s a way of passing data from parent to child?
props.
What shouldn’t you use when creating a static site?
state.
Why shouldn’t you use state in a static site?
State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app, you don’t need it.
What does it mean when building top-down or bottom-up?
You can either start with building the components higher up in the hierarchy (i.e. starting with FilterableProductTable) or with the ones lower in it (ProductRow).
In simpler examples of building a static site, is it best to use a top-down or bottom-up approach?
It’s usually easier to go top-down, and on larger projects, it’s easier to go bottom-up and write tests as you build.
What will you have at the end of building a static site?
A library of reusable components that render your data model.
What’s the only method your components will have at the end of building a static site?
render() methods.
In a static site?? what will the component at the top of the hierarchy (FilterableProductTable) take?
Your data model as a prop.
In a static site?? what will happen if you make a change to your underlying data model and call ReactDOM.render() again?
The UI will be updated. You can see how your UI is updated and where to make changes.
What does React’s one-way data flow (also called one-way binding) do?
Keeps everything modular and fast.
How would you make your UI interactive?
Trigger changes to your underlying data model.
How does React achieve triggering changes to your underlying data model?
With state.
What is the key to thinking about a minimal set of mutable state that your app needs?
DRY: Don’t Repeat Yourself. Figure out the absolute minimal representation of the state your application needs and compute everything else you need on-demand.
Give an example of figuring out the absolute minimal representation of the state your application needs and computing everything else you need on-demand.
If you’re building a TODO list, keep an array of the TODO items around; don’t keep a separate state variable for the count. Instead, when you want to render the TODO count, take the length of the TODO items array.
What are all of the pieces of data in our example application.
insert picture:
The original list of products
The search text the user has entered
The value of the checkbox
The filtered list of products
If these are the pieces of data in our application,
The original list of products
The search text the user has entered
The value of the checkbox
The filtered list of products
How would you figure out which one is state?
By asking three questions about each piece of data:
Is it passed in from a parent via props? If so, it probably isn’t state.
Does it remain unchanged over time? If so, it probably isn’t state.
Can you compute it based on any other state or props in your component? If so, it isn’t state.
Which one of these pieces of data is state?
The original list of products
The search text the user has entered
The value of the checkbox
The filtered list of products
The original list of products is passed in as props, so that’s not state. The search text and the checkbox seem to be state since they change over time and can’t be computed from anything. And finally, the filtered list of products isn’t state because it can be computed by combining the original list of products with the search text and value of the checkbox.
So finally, our state is:
The search text the user has entered
The value of the checkbox
What should you do after you’ve identified what the minimal set of app state is?
Identify which component mutates, or owns, this state.
As React is all about one-way data flow down the component hierarchy, how can you figure out which component should own what state (often the most challenging part for newcomers to understand)?
For each piece of state in your application:
Identify every component that renders something based on that state.
Find a common owner component (a single component above all the components that need the state in the hierarchy).
Either the common owner or another component higher up in the hierarchy should own the state.
If you can’t find a component where it makes sense to own the state, create a new component solely for holding the state and add it somewhere in the hierarchy above the common owner component.
How would you apply the process of figuring out which component should own what state in this app?
insert picture
ProductTable needs to filter the product list based on state and SearchBar needs to display the search text and checked state.
The common owner component is FilterableProductTable.
It conceptually makes sense for the filter text and checked value to live in FilterableProductTable
What should you do when you’ve decided that our state lives in FilterableProductTable.
insert picture…
First, add an instance property this.state = {filterText: ‘’, inStockOnly: false} to FilterableProductTable’s constructor to reflect the initial state of your application.
Then, pass filterText and inStockOnly to ProductTable and SearchBar as a prop.
Finally, use these props to filter the rows in ProductTable and set the values of the form fields in SearchBar.
To support data flowing up, React makes this data flow explicit to help you understand how your program works.
Whats the down side of this?
It requires a little more typing than traditional two-way data binding.
How can we make sure that whenever the user changes the form, we update the state to reflect the user input?
insert picture?
Since components should only update their own state, FilterableProductTable will pass callbacks to SearchBar that will fire whenever the state should be updated. We can use the onChange event on the inputs to be notified of it. The callbacks passed by FilterableProductTable will call setState(), and the app will be updated.
Split last question this up?
sdf?