4

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?

1
  • 2
    As @Sag1v points out below, you can do it, but I recommend that you don't since it is best practice to keep logic out of views, makes it more confusing to read, and will result in a page jump assuming the props and state could update, satisfy the condition, and then the <div /> will appear out of nowhere Commented Dec 6, 2017 at 19:12

1 Answer 1

7

You can do it. it will either return the jsx or null (Won't 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>

Sign up to request clarification or add additional context in comments.

2 Comments

Can I have conditional rendering like {true && true ? <Text>true</Text> : <Text>false</Text> } ? I am trying but it shows me both texts
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.