Main Concepts Flashcards

1
Q

What is the smallest React example?

A

ReactDOM.render(
< h1 >Hello, world!< /h1 >,
document.getElementById(‘root’)
);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is this an example of?

const element = < h1 >Hello, world!< /h1 >;

A

JSX.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is React?

A

A JavaScript library for building user interfaces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is JSX?

A

A syntax extension to JavaScript.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How is JSX not like a template language?

A

Because it comes with the full power of JavaScript.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does JSX produce?

A

React elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does React embrace?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What would React do instead of artificially separating technologies by putting markup and logic in separate files?

A

Separates concerns with loosely coupled units called “components” that contain both.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Does React require JSX?

A

No.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do people find JSX useful?

A

As a visual aid when working with UI inside the JavaScript code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does JSX allow React to do?

A

To show more useful error and warning messages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Declare a variable called name and then use it inside JSX by wrapping it in curly braces.

A
const name = 'Josh Perez';
const element = < h1 >Hello, { name }< /h1 >;

ReactDOM.render(
element,
document.getElementById(‘root’)
);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What can you put inside the curly braces in JSX?

A

Any valid JavaScript expression.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How can we make JSX more readable?

A

By splitting it over multiple lines.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What should you also do when splitting JSX over multiple lines and why?

A

Wrapping it in parentheses to avoid the pitfalls of automatic semicolon insertion.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What happens to JSX after compilation?

A

They become regular JavaScript function calls and evaluate to JavaScript objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What does JSX being compiled mean?

A

You can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Show JSX being used inside an if statement.

A
function getGreeting(user) {
  if (user) {
    return < h1 >Hello, { formatName(user) }!< /h1 >;
  }
  return < h1 >Hello, Stranger.< /h1 >;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How would you specify string literals as attributes?

A

By using quotes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Show an example of using quotes to specify string literals as attributes.

A

const element = < div tabIndex=”0” >< /div >;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How would you embed a JavaScript expression in an attribute?

A

By using curly braces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Show an example of using curly braces to embed a JavaScript expression in an attribute.

A

const element = < img src={ user.avatarUrl } >< /img >;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What should you note about using quotes (for string values) or curly braces (for expressions) in attributes.

A

You should use one or the other, not both at the same time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What naming convention is used for JSX?

A

camelCase.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Show an example of JSX tags containing children.

A
const element = (
  < div >
    < h1 >Hello!< /h1 >
    < h2 >Good to see you here.< /h2 >
  < /div >
);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Is it safe to embed user input in JSX?

A

Yes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Show an example of embedding user input in JSX.

A
const title = response.potentiallyMaliciousInput;
// This is safe:
const element = < h1 >{ title }< /h1 >;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What does ReactDOM do by default with values embedded in JSX?

A

Escapes them before rendering them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What does React DOM escaping any values embedded in JSX before rendering them ensure?

A

You can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What does React DOM escaping any values embedded in JSX before rendering help prevent?

A

XSS (cross-site-scripting) attacks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What does Babel compile JSX down to?

A

React.createElement() calls.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What would this code look like when run through Babel?

const element = (
  < h1 className="greeting" >
    Hello, world!
  < /h1 >
);
A
const element = React.createElement(
  'h1',
  { className: 'greeting' },
  'Hello, world!'
);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What does React.createElement() perform.

A

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!'
  }
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What are the objects created from React.createElement() called?

A

React elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What can you think of React elements as?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What does a element describe?

A

What you want to see on the screen.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

How do DOM elements differ from React elements?

A

They’re plain objects, and are cheap to create.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What takes care of updating the DOM to match the React elements.

A

React DOM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What are elements?

A

They’re what components are made up of.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is a “root” DOM node?

A

A node where everything inside it will be managed by React DOM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

How many root DOM nodes does a React application have?

A

Usually one, unless you are integrating React into an existing app, then you may have as many isolated root DOM nodes as you like.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Ho do you render a React element into a root DOM node?

A

Pass both to ReactDOM.render().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Show an example of rendering a React element into a root DOM node?

A
const element = < h1 >Hello, world< /h1 >;
ReactDOM.render(element, document.getElementById('root'));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What does it mean that React elements are immutable?

A

Once you create an element, you can’t change its children or attributes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Whats a good way of thinking about an element?

A

As a single frame in a movie: it represents the UI at a certain point in time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

How many times do React apps usually call ReactDOM.render()

A

Once.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What does React DOM do after it compares the element and its children to the previous one?

A

Only applies the DOM updates necessary to bring the DOM to the desired state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

How can you verify that React DOM only applies the DOM updates necessary to bring the DOM to the desired state?

A

by inspecting the last example with the browser tools.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What do components let you do?

A

Split the UI into independent, reusable pieces, and think about each piece in isolation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

Conceptually, what are components like?

A

JavaScript functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What do components accepts and return?

A

They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What is the simplest way to define a component?

A

By writing a JavaScript function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

Write a simple component as a JavaScript function.

A
function Welcome(props) {
  return < h1 >Hello, { props.name }< /h1 >;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

Why is this function a valid React component?

function Welcome(props) {
  return < h1 >Hello, { props.name }< /h1 >;
}
A

Because it accepts a single “props” (which stands for properties) object argument with data and returns a React element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

What do we call this type of component?

function Welcome(props) {
  return < h1 >Hello, { props.name }< /h1 >;
}
A

A “function component” because they are literally JavaScript functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

How would you use an ES6 class to define a function component?

A
class Welcome extends React.Component {
  render() {
    return < h1 >Hello, { this.props.name }< /h1 >;
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Show an example of an element that can also represent user-defined components.

A

const element = < Welcome name=”Sara” / >;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

What does React do when it sees an element representing a user-defined component?

A

It passes JSX attributes to this component as a single object called “props”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

How should you always start a components name?

A

With a capital letter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

Why should you always start a components name with a capital letter?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

What does components referring to other components in their output allow?

A

To use the same component abstraction for any level of detail.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

In React how is a button, a form, a dialog, a screen, commonly expressed as?

A

Components.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

Typically, what do new React apps have at the very top?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

When is it a good idea to have reusable components?

A

If a part of your UI is used several times, or is complex enough on its own.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

What should you never do whether you declare a component as a function or a class?

A

Modify its own props.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

What is Reacts single strict rule?

A

All React components must act like pure functions with respect to their props.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

What does State allow in React components?

A

To change their output over time in response to user actions, network responses, and anything else, without violating Reacts single strict rule.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

How is state different to props?

A

It’s private and fully controlled by the component.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

How can you convert a function component to a class?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

When does the render method get called?

A

(at the start) and each time an update happens.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

What are some examples of additional features converting a …. function to a class give us access to?

A

Using local state and lifecycle methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

How could you move ‘date’ from props to state?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

What do you do in applications when components are destroyed?

A

Free up resources they take.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

What is it called when something is rendered to the DOM for the first time?

A

Mounting.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

What is it called when you want to clear something whenever the DOM produced by ……… is removed?

A

Unmounting.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

How would you mount and unmount some code?

A

By declaring special methods on the component class called componentDidMount() and componentWillUnmount()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

What are componentDidMount() and componentWillUnmount() examples of?

A

Lifecycle methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

When does the componentDidMount() method run?

A

After the component output has been rendered to the DOM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

What should you not do with state?

A

Modify it directly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

How should you modify state?

A

By using setState()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

Where do you put this.state?

A

In the constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

What might React do in regards to setState() calls for performance?

A

Batch multiple calls into a single update.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

Why shouldn’t you rely on this.props and this.state values for calculating the next state?

A

Because they may be updated asynchronously.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

Because this.props and this.state may be updated asynchronously, what’s a better way of calculating state?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
85
Q

How would you convert this code to make sure counter is the correct value?

this.setState( {
counter: this.state.counter + this.props.increment,
} );

A

this.setState((state, props) => ( {
counter: state.counter + props.increment
} ));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
86
Q

How would you convert this arrow function to a regular function?

this.setState((state, props) => ( {
counter: state.counter + props.increment
} ));

A
this.setState(function(state, props) { 
  return { 
    counter: state.counter + props.increment
   };
 } );
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
87
Q

What happens when you call setState()

A

React merges the object you provide into the current state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

What happens when your state contain several independent variables, and you update them independently with separate setState() calls?

A

The merging is shallow, so this.setState({x}) leaves this.state.y intact, but completely replaces this.state.x

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

How can a parent or child component know if a certain component is stateful or stateless?

A

They can’t and they shouldn’t care whether it is defined as a function or a class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q

Why is state often called local or encapsulated?

A

It’s not accessible to any component other than the one that owns and sets it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

How can a component pass its sate down to its child components?

A

As props.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
92
Q

< FormattedDate date={ this.state.date } / >

How would The FormattedDate component (that receives the date in its props) know where it came from?

A

It wouldn’t know whether it came from the Clock’s state, from the Clock’s props, or was typed by hand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

What does it mean when something has a “top-down” or “unidirectional” data flow?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
94
Q

If you imagine a component tree as a waterfall of props, continue the analogy for state.

A

Each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
95
Q

In React apps, what is it considered when a component is stateful or stateless?

A

An implementation detail of the component that may change over time. You can use stateless components inside stateful components, and vice versa.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
96
Q

What are some syntactic differences when handling events with React elements vs handling events on DOM elements?

A

React events are named using camelCase, rather than lowercase.
With JSX you pass a function as the event handler, rather than a string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
97
Q

Convert this to a React implementation.

< button onclick=”activateLasers()” >
Activate Lasers
< /button >

A

< button onClick={ activateLasers } >
Activate Lasers
< /button >

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q

How would you prevent default behavior in React?

A

You can’t return false. You must call preventDefault explicitly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
99
Q

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?

A
function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }
  return (
    < a href="#" onClick={handleClick} >
      Click me
    < /a >
  );
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
100
Q

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 >
  );
}
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.

101
Q

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?

A

Just provide a listener when the element is initially rendered.

102
Q

When you define a component using an ES6 class, what is a common pattern in regards to an event handler?

A

For an event handler to be a method on the class.

103
Q

Why do you have to be careful about the meaning of this in JSX callbacks?

A

Because in JavaScript, class methods are not bound by default.

104
Q

What happens if you forget to bind this.handleClick and pass it to onClick?

A

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.

105
Q

Generally, what should you do if you refer to a method without () after it, such as onClick={ this.handleClick }?

A

You should bind that method.

106
Q

If calling bind annoys you, what can you do to get around this?

A
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.
107
Q

Give an example of using the experimental public class fields syntax you can use on class fields to correctly bind callbacks.

A
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 >
    );
  }
}
108
Q

If you aren’t using class fields syntax, give an example of using an arrow function in the callback to correctly bind callbacks.

A
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 >
    );
  }
}
109
Q

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

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.

110
Q

What is it common to do inside of a loop?

A

To want to pass an extra parameter to an event handler.

111
Q

If id is the row ID, show code to delete the row.

A

< button onClick={(e) => this.deleteRow(id, e)} >Delete Row< /button >

or

< button onClick={this.deleteRow.bind(this, id)} >Delete Row< /button >

112
Q

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 >

A

Use an arrow function and Function.prototype.bind respectively.

113
Q

How would you use conditional rendering in React?

A

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.

114
Q

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 >;
}
A
function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return < UserGreeting / >;
  }
  return < GuestGreeting / >;
}

ReactDOM.render(
,
document.getElementById(‘root’)
);

115
Q

What can using variables to store elements help with?

A

Conditionally rendering a part of the component while the rest of the output doesn’t change.

116
Q

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?

A

Conditionally including an element.

117
Q

in JavaScript, what does ‘true & & expression’ and ‘false & & expression’ always evaluates to?

A

expression and false respectively.

118
Q

What happens if the condition is true and false?

A

If it’s true the element right after & & will appear in the output. If it is false, React will ignore and skip it.

119
Q

Show a simple example of rendering elements inline is to use the JavaScript conditional operator.

A

condition ? true : false

120
Q

Use the JavaScript conditional operator to conditionally render a small block of text.

A
render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    < div >
      The user is < b >{ isLoggedIn ? 'currently' : 'not' }< /b > logged in.
    < /div >
  );
}
121
Q

What is something you should consider whenever conditions become too complex?

A

Extracting a component.

122
Q

How would you make a component hide itself even though it was rendered by another component?

A

Return null instead of its render output.

123
Q

Show an example of how you would make a component hide itself even though it was rendered by another component?

A
function WarningBanner(props) {
  if (!props.warn) {
    return null;
  }
.......
Here, If the value of the prop is false, then the component does not render.
124
Q

What is something to note when returning null from a component’s render method?

A

It doesn’t affect the firing of the component’s lifecycle methods. For instance componentDidUpdate will still be called.

125
Q

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.

A
const numbers = [ 1, 2, 3, 4, 5 ];
const doubled = numbers.map((number) => number * 2);
console.log(doubled);
126
Q

In React, how would you transform arrays into lists of elements.

A

By using .map()

127
Q

Show how you would render a list of items in an array not in a component.

A
const numbers = [ 1, 2, 3, 4, 5 ];
const listItems = numbers.map((number) =>
  < li >{ number }< /li >
);

ReactDOM.render(
< ul >{ listItems }< /ul >,
document.getElementById(‘root’)
);

128
Q

Show how you would render a list of items in an array in a component without a key.

A
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')
);
129
Q

What is a key?

A

A special string attribute you need to include when creating lists of elements.

130
Q

Show how you would render a list of items in an array in a component with a key.

A
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')
);
131
Q

What do keys do?

A

Help React identify which items have changed, are added, or are removed.

132
Q

Where should keys be given to, and why?

A

Elements inside the array to give the elements a stable identity.

133
Q

What’s the best way to pick a key?

A

Use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:

134
Q

Show an example of picking a key.

A
const todoItems = todos.map((todo) =>
  < li key={ todo.id } >
    { todo.text }
  < /li >
);
135
Q

How can you name a key when you don’t have stable IDs for rendered items.

A

As a key as a last resort, you can use the item index .

136
Q

Show an example of naming a key via its item index.

A

const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
< li key={ index } >
{ todo.text }
< /li >
);

137
Q

When is it not recommended to use indexes for keys?

A

When the order of items may change.

138
Q

Why is it bad to use indexes for keys where the order of the items may change?

A

Because they can negatively impact performance and may cause issues with component state.

139
Q

What happens if you choose not to assign an explicit key to list items?

A

React will default to using indexes as keys.

140
Q

Keys only make sense in the context of the surrounding array. Give an example expanding on this.

A

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.

141
Q

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')
);
A
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')
);
142
Q

What’s a good rule of thumb in regards to keys?

A

That elements inside the map() call need keys.

143
Q

What should be noted regarding uniqueness of keys used within arrays?

A

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.

144
Q

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?

A

Pass it explicitly as a prop with a different name.

145
Q

Show an example of passing a key explicitly as a prop with a different name to a component.??

A
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.

146
Q

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 >
  );
}
A
function NumberList(props) {
  const numbers = props.numbers;
  return (
    < ul >
      { numbers.map((number) =>
        < ListItem key={ number.toString() }
                  value={ number } / >
  )}
< /ul >   ); }
147
Q

Whats something to keep in mind if the map() body is too nested?

A

It might be a good time to extract a component.

148
Q

What is extracting components?

A

Splitting components into smaller components.

149
Q

Why do HTML form elements work a little bit differently from other DOM elements in React?

A

Because form elements naturally keep some internal state.

150
Q

Create an HTML form that accepts a single name.

A
< form >
  < label >
    Name:
    < input type="text" name="name" / >
  < /label >
  < input type="submit" value="Submit" / >
< /form >
151
Q

What behavior will this form have?

< form >
  < label >
    Name:
    < input type="text" name="name" / >
  < /label >
  < input type="submit" value="Submit" / >
< /form >
A

Default HTML form behavior.

152
Q

What is the default HTML form behavior?

A

Browsing to a new page when the user submits the form.

153
Q

What is the default behavior of React with regards to forms??

A

The same as HTML.

154
Q

In most cases with forms in React, what is the desired process?

A

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.

155
Q

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?

A

With a technique called “controlled components”.

156
Q

In HTML, how is state maintained in form elements such as < input >, < textarea >, and < select >

A

They typically maintain their own state.

157
Q

In HTML, how is state updated in form elements such as < input >, < textarea >, and < select >

A

Updates are based on user input.

158
Q

In React, where is mutable state is typically kept?

A

In the state property of components, and only updated with setState()

159
Q

In regards to controlled components, how should React state be thought of?

A

As the “single source of truth”.

160
Q

What does the React component that renders a form also control?

A

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”.

161
Q

Write an example of logging a name from a form when it is submitted as a controlled component.

A
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 >
    );
  }
}
162
Q

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 >
    );
  }
}
A

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.

163
Q

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 >
    );
  }
}
A

Since handleChange runs on every keystroke to update the React state, the displayed value will update as the user types.

164
Q

In a controlled component, what will every state mutation have?

A

An associated handler function.

165
Q

With a controlled component, why would you want every state mutation to have an associated handler function.?

A

To make it straightforward to modify or validate user input.

166
Q

Write a handleChange to make sure that names are written with all uppercase letters.

A

handleChange(event) {
this.setState( { value: event.target.value.toUpperCase() } );
}

167
Q

In HTML, what does a < textarea > element define?

A

Its text by its children.

168
Q

How does < textarea > differ in React compared to HTML?

A

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.

169
Q

Show a simple example of writing a < textarea > in React with an attribute.

A

< 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.

170
Q

In HTML, what does < select > do?

A

Create a drop-down list.

171
Q

Show a simple example of how you would create a drop-down list of flavors in HTML.

A

< select >
< option value=”grapefruit” >Grapefruit< /option >
< option value=”lime” >Lime< /option >
< option selected value=”coconut” >Coconut< /option >
< option value=”mango” >Mango< /option >
< /select >

172
Q

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 >

A

It uses a value attribute on the root select tag.

173
Q

Why is it more convenient for React to use a value attribute on the root select tag instead of the selected attribute?

A

Because you only need to update it in one place.

174
Q

Show a simple example of a React form that uses a selected attribute.

A

< 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 >

175
Q

What is something to note with < input type=”text” >, < textarea >, and < select > in regards to React?

A

They all work very similarly - they all accept a value attribute that you can use to implement a controlled component.

176
Q

What is something to nor in regards to the value attribute in a React form?

A

That you can pass an array into the value attribute, allowing you to select multiple options in a select tag.

177
Q

Show a simple example of using an array in the value attribute of a React form.

A

< select multiple={ true } value={ [‘B’, ‘C’] } >

178
Q

In HTML, what does an < input type=”file” > allow you to do?

A

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.

179
Q

What is the value of this input in HTML?

< input type=”file” / >

A

Read-only, meaning it’s an uncontrolled component in React.

180
Q

What can you do if you need to handle multiple controlled input elements?

A

Add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

181
Q

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.

A
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
});

182
Q

What is this ES6’s, ES5 equivalent?

this.setState({
[name]: value
});

A
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.

183
Q

What does specifying the value prop on a controlled component do?

A

Prevents the user from changing the input unless you desire so.

184
Q

If you’ve specified a value but the input is still editable, what might you have done?

A

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);

185
Q

Why is it sometimes tedious to use controlled components?

A

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.

186
Q

When can using controlled components be particularly tedious?

A

When you are converting a preexisting codebase to React, or integrating a React application with a non-React library.

187
Q

What is an alternative to using controlled components for implementing input forms?

A

Uncontrolled components.

188
Q

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.

A

Formik.

189
Q

What principals is Formik built on?

A

The same principles of controlled components and managing state.

190
Q

What is recommended when several components need to reflect the same changing data?

A

Lifting the shared state up to their closest common ancestor.

191
Q

LIFTING STATE UP

A

Write notes.

192
Q

Is using composition or inheritance recommended to reuse code between components?

A

Composition as React has a powerful composition model.

193
Q

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”)?

A

That the components use the special children prop to pass children elements directly into their output.

194
Q

Show an example of components using the special children prop to pass children elements directly into their output.

A
function FancyBorder(props) {
  return (
    < div className={ 'FancyBorder FancyBorder-' + props.color } >
      { props.children }
    < /div >
  );
}
195
Q

What does using the special children prop to pass children elements directly into their output allow?

A

Other components to pass arbitrary children to them by nesting the JSX.

196
Q

Show an example of other components passing arbitrary children to them by nesting the JSX.

A
function WelcomeDialog() {
  return (
    < FancyBorder color="blue" >
      < h1 className="Dialog-title" >
        Welcome
      < /h1 >
      < p className="Dialog-message" >
        Thank you for visiting our spacecraft!
      < /p >
    < /FancyBorder >
  );
}
197
Q

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 >
  );
}
A

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.

198
Q

Although less common, what should you do if you need multiple “holes” in a component?

A

Come up with your own convention instead of using children.

199
Q

Show an example of needing multiple “holes” in a component.

A
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 / >
      } / >
  );
}
200
Q

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 / >
      } / >
  );
}
A

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.

201
Q

Show an example of how sometimes we can think about components as being “special cases” of other components.

A

We might say that a WelcomeDialog is a special case of Dialog.

202
Q

In React, how else are “special cases” components achieved??

A

By composition, where a more “specific” component renders a more “generic” one and configures it with props.

203
Q

Show an example of composition in React.

A
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!" / >

);
}

204
Q

Show an example of composition working with components defined as classes.

A
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 }!);
}
}

205
Q

Is there a time where creating component inheritance hierarchies is better than composition.

A

No.

206
Q

What does props and composition give you?

A

All the flexibility you need to customize a component’s look and behavior in an explicit and safe way.

207
Q

What is good to remember in regards to what components may accept?

A

They may accept arbitrary props, including primitive values, React elements, or functions.

208
Q

What should you do if you want to reuse non-UI functionality between components?

A

Extract it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.

209
Q

What’s a good process when thinking in React.

A
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
210
Q

Whats an example of a JSON mock?

A

[
{ 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” }
];

211
Q

How would you break The UI Into A Component Hierarchy?

A

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!

212
Q

But how do you know what should be its own component?

A

Use the same techniques for deciding if you should create a new function or object. One such technique is the single responsibility principle.

213
Q

What is the single responsibility principle?

A

A component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents.

214
Q

What is something you will find if you’re often displaying a JSON data model to a user if your model was built correctly?

A

your UI (and therefore your component structure) will map nicely.

215
Q

Why would your UI (and therefore your component structure) map nicely if your model was built correctly?

A

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.

216
Q

split last question?

A

asdf

217
Q

Import Image.

A

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

218
Q

Import Image. 2

A

asdf

219
Q

Import Image. 3

A

asdf

220
Q

Import Image. 4

A

sadf

221
Q

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.

A

FilterableProductTable

 - SearchBar
 - ProductTable
      - -ProductCategoryRow
      - -ProductRow
222
Q

After you have your component hierarchy, what’s the best way to implement your app.

A

To build a version that takes your data model and renders the UI but has no interactivity.

223
Q

Why is it best to build a version of your app that takes your data model and renders the UI but has no interactivity.

A

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.

224
Q

What will you want when you build a static version of your app that renders your data model?

A

Build components that reuse other components and pass data using props.

225
Q

What’s a way of passing data from parent to child?

A

props.

226
Q

What shouldn’t you use when creating a static site?

A

state.

227
Q

Why shouldn’t you use state in a static site?

A

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.

228
Q

What does it mean when building top-down or bottom-up?

A

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).

229
Q

In simpler examples of building a static site, is it best to use a top-down or bottom-up approach?

A

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.

230
Q

What will you have at the end of building a static site?

A

A library of reusable components that render your data model.

231
Q

What’s the only method your components will have at the end of building a static site?

A

render() methods.

232
Q

In a static site?? what will the component at the top of the hierarchy (FilterableProductTable) take?

A

Your data model as a prop.

233
Q

In a static site?? what will happen if you make a change to your underlying data model and call ReactDOM.render() again?

A

The UI will be updated. You can see how your UI is updated and where to make changes.

234
Q

What does React’s one-way data flow (also called one-way binding) do?

A

Keeps everything modular and fast.

235
Q

How would you make your UI interactive?

A

Trigger changes to your underlying data model.

236
Q

How does React achieve triggering changes to your underlying data model?

A

With state.

237
Q

What is the key to thinking about a minimal set of mutable state that your app needs?

A

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.

238
Q

Give an example of figuring out the absolute minimal representation of the state your application needs and computing everything else you need on-demand.

A

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.

239
Q

What are all of the pieces of data in our example application.

insert picture:

A

The original list of products
The search text the user has entered
The value of the checkbox
The filtered list of products

240
Q

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?

A

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.

241
Q

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

A

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

242
Q

What should you do after you’ve identified what the minimal set of app state is?

A

Identify which component mutates, or owns, this state.

243
Q

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)?

A

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.

244
Q

How would you apply the process of figuring out which component should own what state in this app?

insert picture

A

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

245
Q

What should you do when you’ve decided that our state lives in FilterableProductTable.

insert picture…

A

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.

246
Q

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?

A

It requires a little more typing than traditional two-way data binding.

247
Q

How can we make sure that whenever the user changes the form, we update the state to reflect the user input?

insert picture?

A

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.

248
Q

Split last question this up?

A

sdf?