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:
Article No Longer Available
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.
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.
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)
I would rather use
isFirstTrue
instead offirstIsTrue
to make the variable name sound boolean.Thanks Silvia for the post!
On a second thought I think I would also go with "isFirstTrue". Hope it helped :).
Yes,your articles are helpful.
I was just thinking about how to implement ternary operators in React. Flagging this for later.
I hope it helped make things a bit clearer :).
there are some libraries that can help us with that. as mayre or choose from react-extras. :)
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?