Conditionally render multiple elements in React

avatar

Borislav Hadzhiev

Fri Apr 22 20222 min read

banner

Photo by liane

Conditionally render multiple elements in React #

Use a ternary operator to conditionally render multiple elements in React. When returning multiple sibling elements, make sure to wrap them in a React fragment.

App.js
export default function App() { const str = 'hi'; return ( <div> {str.length === 2 ? ( <> <h2>First</h2> <h2>Second</h2> </> ) : null} </div> ); }

We used a ternary operator to conditionally render multiple elements.

The ternary operator is very similar to an if/else statement.

If the value to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise the value to the right of the colon is returned.

App.js
const result1 = 5 === 5 ? 'yes' : 'no'; console.log(result1); // 👉️ "yes" const result2 = 5 === 10 ? 'yes' : 'no'; console.log(result2); // 👉️ "no"

If the string hi has a length of 2 characters, we return the DOM elements, otherwise false is returned.

Notice that we wrapped the sibling elements in a React fragment.

Fragments are used when we need to group a list of children without adding extra nodes to the DOM.

You might also see the more verbose syntax of fragments being used.

App.js
import React from 'react'; export default function App() { const str = 'hi'; return ( <div> {str.length === 2 ? ( <React.Fragment> <h2>First</h2> <h2>Second</h2> </React.Fragment> ) : null} </div> ); }

The two examples above achieve the same result - they group the list of children elements without adding extra nodes to the DOM.

You might also see examples online that use the logical AND (&&) operator to conditionally render multiple elements.

App.js
export default function App() { const str = 'hi'; return ( <div> {str.length === 2 && ( <> <h2>First</h2> <h2>Second</h2> </> )} </div> ); }

The logical AND (&&) operator returns the value to the left if it's falsy, otherwise the value to the right is returned.

The falsy values in JavaScript are: null, undefined, 0, false, "" (empty string), NaN (not a number).

Notice that 0 is a falsy value, so if you try to conditionally check for an array's length using logical AND (&&), you might end up rendering a 0.

App.js
export default function App() { const arr = []; return ( <div> {arr.length && ( <> <h2>arr[0]</h2> <h2>arr[1]</h2> </> )} </div> ); }

If you load the example, you'll see that it renders 0. The reason being - 0 is a falsy value, so it gets returned from the logical AND (&&) operator.

One way to get around this is to explicitly check if the array's length is greater than 0.

App.js
export default function App() { const arr = []; return ( <div> {arr.length > 0 && ( <> <h2>arr[0]</h2> <h2>arr[1]</h2> </> )} </div> ); }

The example above won't render anything because the array's length is 0. This is the expected behavior.

Use the search field on my Home Page to filter through my more than 1,000 articles.