So far, we've used React as a static rendering engine. Now, we're going to add state to make React components more dynamic.
The key difference between props and state is that state is internal and controlled by the component itself while props are external and controlled by whatever renders the component. Let's see it in practice.
Implement the function getInitialState
, which returns... the initial state of the component. This is an object map of keys to values.
getInitialState: function() {
return {
clicks: 0
};
}
To access a component's state, use this.state
, just like how we use this.props
.
To update a component's state, call this.setState
with an object map of keys to updated values. Keys that are not provided are not affected.
this.setState({
// Notice how we access the current state here
clicks: this.state.clicks + 1
})
When a component's state changes, render
is called with the new state and the UI is updated to the new output. This is the heart of React. We'll take a closer look in the next article.
You may be surprised that we don't need to pass the callback as this.onCowClick.bind(this)
. (If not, read this). This is because React autobinds methods on the component instance for performance reasons. Read more here.
Edit this board picker so the button actually works. Right now, the first board is always selected (var isSelected = ii === 0
).
Components, props, and state form the core of React. You're ready to build with React!
To finish the core lessons, we'll take a look under the hood to understand how React works.
Subscribe for a range of articles from React basics to advanced topics such as performance optimization and deep dives in the React source code.