class set state code example
Example 1: set state
class App extends React.Component {
state = { count: 0 }
handleIncrement = () => {
this.setState({ count: this.state.count + 1 })
}
handleDecrement = () => {
this.setState({ count: this.state.count - 1 })
}
render() {
return (
<div>
<div>
{this.state.count}
</div>
<button onClick={this.handleIncrement}>Increment by 1</button>
<button onClick={this.handleDecrement}>Decrement by 1</button>
</div>
)
}
}
Example 2: this setstate previous state react
state = {count: 0}
increment = () => {
this.setState(previousState => ({
count: previousState.count + 1
}))
}
Example 3: set state
setState({ searchTerm: event.target.value })