In React Docs, handling events article: how state is being updated to the opposite boolean value, I have a question.
Why do we need to add .isToggleOn
after isToggleOn: !prevState
Why can't I just simply write isToggleOn: !prevState
?
prevState
is {isToggleOn: true}
. So !prevState
should be {isToggleOn: false}
. Am I right?
It confuses me, because it sounds like {property: opposite of the boolean.property}
.
I know what prevState is and I know .setState() is updating the state. Please help me better understand this. Thank you so much in advance!
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);