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

后端 未结 3 616
南笙
南笙 2021-01-31 07:46

I\'m trying to render a div on the same page when the user clicks on a link.

My HTML page:

Stores&l

相关标签:
3条回答
  • 2021-01-31 08:17

    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 = {diplay: 'block'}
    const NONE= {diplay: 'none'}
    
    // in render
    {this.state.showStore ? BLOCK : NONE}
    
    0 讨论(0)
  • 2021-01-31 08:19

    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' }}
    
    0 讨论(0)
  • 2021-01-31 08:39

    You can also conditionally create the element via

       { 
         this.state.showStore 
         ? <div className="row account stores">
            <div>a lot more divs</div>
           </div> 
         : null 
       }
    
    0 讨论(0)
提交回复
热议问题