Listing 4-12: Using state and setState in a Class Component
The current count is: 0.
import {Component} from 'react';
class ClassComponentState extends Component {
constructor(props){
super(props);
this.state = {count: 0};
this.incrementCount = this.incrementCount.bind(this);
}
incrementCount(){
this.setState({count: this.state.count + 1});
}
render(){
return (
<div>
<p>The current count is: {this.state.count}.</p>
<button onClick = {()=>{this.incrementCount()}}>
Add 1
</button>
</div>
);
}
}
export default ClassComponentState;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.