Reputation: 1788
I figure out what is the problem with the true/false
condition in the handleToggleClick()
method...
When the button once clicked, the second click it does not want to recorgonize (still false
state in the variable prop showWarning
).
function WarningBanner(props) {
if (!props.warn) {
return null;
}
return (
<div className="warning">
Warning!
</div>
);
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {showWarning: true};
this.handleToggleClick = this.handleToggleClick.bind(this);
}
handleToggleClick() {
this.setState(prevState => ({
showWarning: true ? false : true // this is where I have a problem.
}));
}
render() {
return (
<div>
<WarningBanner warn={this.state.showWarning} />
<button onClick={this.handleToggleClick}>
{this.state.showWarning ? 'Hide' : 'Show'}
</button>
</div>
);
}
}
ReactDOM.render(
<Page />,
document.getElementById('root')
);
Upvotes: 0
Views: 197
Reputation: 138277
true ? false : true
Thats always false
as true
is always truthy and the ternary always enters the first expression. You may want:
showWarning: !showWarning
Or if you really need the ternary:
showWarning: showWarning ? false : true
Upvotes: 3