DEV Community

Cover image for Conditional rendering in React - using the ternary operator
Arika O
Arika O

Posted on • Updated on

Conditional rendering in React - using the ternary operator

In the last article we discussed how to conditionally render parts of our React application using if/ else statements. You can find more about it in the link below:

Today I'm going to write about the ternary operator method. For simplicity, I am going to use code similar with the one in last article. We have three functional components, App, Condition1 and Condition2. App will render one of the other two components, depending the state of the button.

Alt Text

Alt Text

Alt Text

One could ask, why use the ternary operator when we can achieve the exact same thing using an if/ else statement? I do not have a particular preference for this method but I believe it makes the conditional rendering easier to read and gives us the possibility to use it inline in our return statement. Of curse, there are cases when the code becomes bloated (when trying to render more than one HTML element/ React components at a time) so in this case you should consider extracting the code in a different component.

In the example bellow, App is rendering three components at the same time, if the first condition is true. In this case, don't forget to add a wrapper around the components (I used a fragment, but you can use a div or any other HTML element that makes syntactical sense) and to also add parenthesis around the return statements. If it's just a single component, you can omit the parentheses, as seen in the example above.

Alt Text

In case you want to plat around with the code, you can find the complete example here: https://codesandbox.io/s/conditional-rendering-using-the-ternary-operator-wkwsw?file=/src/App.js

Top comments (7)

Collapse
 
creativesuraj profile image
Suraj Sharma

I would rather use isFirstTrue instead of firstIsTrue to make the variable name sound boolean.

Thanks Silvia for the post!

Collapse
 
arikaturika profile image
Arika O

On a second thought I think I would also go with "isFirstTrue". Hope it helped :).

Collapse
 
creativesuraj profile image
Suraj Sharma

Yes,your articles are helpful.

Collapse
 
scrabill profile image
Shannon Crabill

I was just thinking about how to implement ternary operators in React. Flagging this for later.

Collapse
 
arikaturika profile image
Arika O

I hope it helped make things a bit clearer :).

Collapse
 
jjeduardods profile image
João Eduardo

there are some libraries that can help us with that. as mayre or choose from react-extras. :)

Collapse
 
arikaturika profile image
Arika O

Thx for the tip. I'm not super familiar with React so I didn't have the chance to use them yet. What exactly Mayre do?