How to show CSS: not in conditional case with React JSX?

I am trying to display a div on the same page when the user clicks on the link.

My HTML page:

 <div class="stores"> <h1>Stores</h1> <ul class="stores"> <li><a href="#" onClick={this.onClick} >Store A</a></li> <li>Store B</li> <li>Store C</li> </ul> </div> 

My components/store.js.jsx :

 var Store = React.createClass({ getInitialState: function() { return { showStore: false }; }, onClick: function() { this.setState({ showStore: true }); }, render: function() { return( <div className="row account stores" style={{display: { this.state.showStore ? 'block' : 'none'} }}> <div>a lot more divs</div> </div> ); } }); 

But I get:

Syntax Error: unknown: Unexpected token

For this line:

 style={{display: { this.state.showStore ? 'block' : 'none'} }} 

How can I conclude conditionally inside a style?

+7
javascript reactjs
source share
2 answers

This is due to the misuse of the ternary operator. See the documentation here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

You should not end it with {} , as you did.

Try the following:

 style={{display: this.state.showStore ? 'block' : 'none' }} 
+21
source share

You can also conditionally create an element using

  { this.state.showStore ? <div className="row account stores"> <div>a lot more divs</div> </div> : null } 
+1
source share

All Articles