How to CSS display:none within conditional with React JSX?

JavascriptReactjs

Javascript Problem Overview


I'm trying to render a div on the same page when the user clicks on a 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 a:

> SyntaxError: unknown: Unexpected token

For this line:

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

How can I nest conditionally inside a style?

Javascript Solutions


Solution 1 - Javascript

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

You should not wrap it with {} as you have done.

Try the following:

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

Solution 2 - Javascript

You can also change a classname and style in CSS.

// outside render
const NORMAL = "row account stores"
const HIDDEN = NORMAL + " hidden"

// In render
render: function() {
  return(
    <div className={this.state.showStore ? NORMAL : HIDDEN}>
      <div>a lot more divs</div>
        </div>
  );
}

Note that it is generaly better to not use double curly braces {{ in render function as you are often creating a new object on every render execution. for example:

{display: true ? 'block' : 'none' } === {display: true ? 'block' : 'none' } // false

// outside render
const BLOCK = { display: 'block' }
const NONE= { display: 'none' }

// in render
{this.state.showStore ? BLOCK : NONE}

Solution 3 - Javascript

You can also conditionally create the element via

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStandardNerdView Question on Stackoverflow
Solution 1 - JavascriptctrlplusbView Answer on Stackoverflow
Solution 2 - JavascriptcquezelView Answer on Stackoverflow
Solution 3 - Javascript00500005View Answer on Stackoverflow