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,
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