As per the React Docs we can have two ways for setState one with object syntax and other with function which they have shown as below
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
My understanding of arrow function syntax is like () => {}
where flower brackets are followed after arrow =>
, but as per the sample it is round braces instead of flower brackets
What is the difference between these syntax ()=>{}
and ()=>({})
.
Sample Code tried as per the docs which is working when this.setStage(prevStage=>({}))
syntax is used in handleClick
function, and if you change it to this.setState(prevStage=>{})
it wont toggle the button value.
Below is the working code:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn : true
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<div>
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : OFF}
</button>
</div>
);
}
}