DEV Community

Cover image for Conditional Rendering Caveats in React
Gabriel-Ionut Enache
Gabriel-Ionut Enache

Posted on

Conditional Rendering Caveats in React

When components need to display different things depending on different conditions, typically we would use the &&(logical and) operator.

Say we have a list or products and we want to display our list of products in JSX and therefore, on our web page. Pretty easy, right? Now… what happens if the list of products is empty?

Using the && operator

Using the && operator, as you would have probably guessed, 0 is rendered on the page. That's because when Javascript evaluates products.length which is 0 with anything else, the whole result of the expression will be 0.

Solution

Use the conditional(ternary operator) so you can explicitly tell JSX what to render based on a true or false expression.
Using the ternary operator

Using the ternary operator

Top comments (0)