Jessica Robertson
Jessica Robertson

Reputation: 427

Toggle variable upon onClick in JSX

I have a default state in my constructor

this.state {
    showModal:false
}

then how can I toggle the value without declaring a function, but straight away do that in JSX? I found it's too much of code to do it in a function. Can't it be more simple just do it like

render(){
    return(<div onClick={()=>this.setState({showModal:!showModal})}></div>)
}

But I got error of syntax error in my JSX above. Why?

Upvotes: 0

Views: 74

Answers (1)

bejado
bejado

Reputation: 1460

Remember, React state is maintained in the this.state property, thus you need to reference this.state.showModal, not this.showModal.

The correct way to do this:

<div onClick={() =>
    this.setState({showModal: !this.state.showModal})}>
</div>

As for doing this only using JSX (without declaring a function), that isn't possible. JSX is JavaScript.

Upvotes: 2

Related Questions