ReactJS - Elegant way to toggle state
Although this was a little challenge for me but I ended up like this --
class Toggle extends React.Component{
constructor(props){
super(props);
this.handleToggleVisib = this.handleToggleVisib.bind(this);
this.state = {
visib : false
}
}
handleToggleVisib(){
this.setState({ visib : !this.state.visib });
}
render(){
return(
<div>
<h1>Toggle Built</h1>
<button onClick={this.handleToggleVisib}>
{this.state.visib? 'Hide Button' : 'Show Button'}
</button>
<div>
{this.state.visib && <p>This is a tough challenege</p>}
</div>
</div>
);
}
}
ReactDOM.render(<Toggle />,document.getElementById('app'));
I think that @mark-anderson's answer is the most "elegant" way, however, the recommended way of doing a state toggling (according to React docs) is:
this.setState(prevState => ({
iover: !prevState.iover
}));
*If you need to store 'show/hide' inside that state, the code would be:
this.setState(prevState => ({
iover: prevState.iover === 'hide' ? 'show' : 'hide'
}));
One way to do this is to keep your state as a boolean true or false then put a ternary operator wherever you want the value "hide" or "show". For example:
getInitialState: function() {
return {
iover: false
};
},
handleClick: function() {
this.setState({
iover: !this.state.iover
});
},
render: function(){
return (
<div className={this.state.iover ? 'show' : 'hide'}>...</div>
);
}