Can I use multiple booleans for conditional rendering in React?

11,186

You can do it. it will either return the jsx or null (Wont render anything).

Example when condition is true:

const App = () => (
  <div>
    {true && true && <div> Hello! </div>}
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Example when condition is false:

const App = () => (
  <div>
    {true && false && <div> Hello! </div>}
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Share:
11,186
user3802348
Author by

user3802348

Updated on June 05, 2022

Comments

  • user3802348
    user3802348 almost 2 years

    I want to do something like the following in a React component:

    <div>
        {this.props.isOpen && this.state.isReady && <div> Hello! </div>}
    </div>
    

    Is it possible to use multiple booleans for conditionally rendering components in React? Could this ever possibly render a boolean to the user?

  • user0810
    user0810 over 4 years
    Can I have conditional rendering like {true && true ? <Text>true</Text> : <Text>false</Text> } ? I am trying but it shows me both texts
  • user0810
    user0810 over 4 years
    quick tip if you get something like this {false && true ? <Text>true</Text> : <Text>false</Text> } it will return text false but when you write {false && (true ? <Text>true</Text> : <Text>false</Text>) } (with brackets) it will return nothing. I wanted the second option and I couldnt understand why I get text false