Can I use multiple booleans for conditional rendering in React?

user3802348 picture user3802348 · Dec 6, 2017 · Viewed 7.9k times · Source

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?

Answer

Sagiv b.g picture Sagiv b.g · Dec 6, 2017

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>