October 14, 2018

Reactjs | Toggle in Reactjs

Today we will see how we can do toggle functionality in Reactjs. 

Code Example: https://codesandbox.io/s/520z9kpkox


For this code, we will make only one smart component Toggle.js and that will do all work.



1) For this, we need to set the flag isToggle in the state to false.


this.state = {
isToggle: true
};

2) We will create a function - handleToggle to handle the click event. Which will toggle the value of the button :



handleToggle = () => {
this.setState(function(prevState) {
console.log(prevState);
return { isToggle: !prevState.isToggle };
});
};


3) This is how your JSX will look:



render() {
return (
<button onClick={this.handleToggle}>{this.state.isToggle ? 1 : 0}</button>
);
}









No comments: