CraZyDroiD
CraZyDroiD

Reputation: 7105

Toggle the state value with a click in React

I'm displaying a certain div when a user clicks a button(really an image)

<img src={notification} className="search_bar_icons" onClick={this.props.open_notifications}/>

When the user clicks this image i'm changing the state of the div i want to show to 'true'

open_notification() {
    this.setState({
        showNotification: true,
    });
}

This is working correctly. But i want to set state as 'false', if the user clicks the image again. How can i do this?

Upvotes: 1

Views: 2213

Answers (1)

Andrii Starusiev
Andrii Starusiev

Reputation: 7764

You can toggle your value with

this.setState({ showNotification: !this.state.showNotification });

Update. For now, a better approach of using previous state inside of the setState is:

this.setState(prevState => ({ showNotification: !prevState.showNotification }));

Upvotes: 7

Related Questions