
Adding a state to a component
One can say that React barely has any API. It has about 9-10 methods and that is all we get.
The State is one of the main APIs in React. The best place to define the initial state of a component is in the class constructor.
Create a class component and initialize its state:
class Button extends React.Component
{
constructor(props){
super(props)
this.state = {text: 'OFF'}
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
this.state.text === 'OFF' ? this.setState({text: 'ON'}) :
this.setState({text: 'OFF'})
}
render() {
return (
<button type="button" onClick={this.handleClick}>
{this.state.text}</button>)
}
}
This is an example of an internal state of a button that changes its text on user click (it toggles between ON and OFF).
A few things are required for that component to maintain a state:
- We defined the state in the class constructor method. This is the first entry of the class that will be executed. We can think of that definition as the default state of the component.
- We created a handleClick() method and bound it to the this class in the class constructor. It will fire when the user clicks on the button.
- In the handleClick method, we used one of the React's APIs--this.setState--and based on the comparison of the current state, we set our new state.
- In the button, we added a simple JavaScript event--onClick. Here, React has a slightly different syntax on events; it uses camel case. onClick becomes onClick.
The second form of the setState() method is passing a function in the state instead of an object; in the callback, we get the previous state:
this.setState
(function(prevState) {
return {
text: prevState.text === 'OFF' ? 'ON' : 'OFF'
};
});
Alternatively, an arrow ES6 function can be used:
this.setState((prevState) => ({
text: prevState.text === 'OFF' ? 'ON' : 'OFF'
}));
Other React methods.
A few other important React APIs are the component life cycles methods:
class Greeting extends React.Component {
constructor(props) {
super(props);
console.log('constructor');
}
componentDidMount() {
console.log('componentDidMount');
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
render() {
return (
<div>
<p>{this.props.name}</p>
{this.props.children}
</div>)
}
}
Let's test these life cycle methods by adding a simple button to the body of the HTML:
<button onclick="umountComponent()">Unmount</button>
Also, we can define that function in the JavaScript tag, as follows:
function umountComponent(){
ReactDOM.unmountComponentAtNode(document.getElementById('root'))
}
When the app is loaded, the order of the events is as follows:
- Constructor method is called.
- componentDidMount() is called when the component is mounted to a parent or directly to the DOM.
- componentWillUnmount() is called just before the component will unmount from the DOM.
A simple use of these events can be as shown:
- Constructor: Initialize the component's default state in the constructor.
- componentDidMount(): The component is ready. You can perform any actions at that point.
- componentWillUnmount(): The component will be detached from the DOM; here, you can clear any resources that may cause memory leaks.