State
Props are immutable and are controlled by the parent component. In React, every class component has a state property used for self-managed and mutable data. Like props
, state
is just a plain JavaScript object.
To set the default starting state, you can declare the state as a class field, thanks to Webpack, or set it in the constructor instead:
class Parent extends React.Component { state = { greet: 'Props and State', }; onUpdate = () => { console.log('Child triggered callback'); }; render() { return ( <div> <Child text={this.state.greet} onUpdate={this.onUpdate} /> </div> ); } }
Â
Â
The parent component sets a greet
key on the initialized state object with an initial value. Then the state object is used in the render method to pass down the text
as a prop to the child component.
setState
To mutate state, you use React's setState
method available to you as part of the React.Component
 base class. The simplest usage is to...