0

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?

2
  • @bejado won't work too Commented Feb 12, 2017 at 5:29
  • What error are you getting? Commented Feb 12, 2017 at 5:33

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.