Using a condition inside map() in React

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
5 min

banner

# Table of Contents

  1. Use a condition inside map() in React
  2. Break a map() loop (map() only part of Array) in React

# Use a condition inside map() in React

To use a condition inside map() in React:

  1. Call the map() method on an array.
  2. Use an if condition that explicitly returns if it's satisfied.
  3. Otherwise return a different value or return null to render nothing.
App.js
export default function App() { const arr = [1, 2, 3, 4, 5, 6]; return ( <div> {arr.map((element, index) => { if (element % 2 === 0) { return <h2 key={index}>{element}</h2>; } return <h2 key={index}>X</h2>; })} </div> ); }

use condition inside map in react

We used the Array.map() method to iterate over an array.

The function we passed to map() gets called with each element in the array and the index of the current iteration.

On each iteration, we check if the element is divisible by 2 and if it is, we return the element, otherwise, we return X.

If you get the error that map() is not a function in React, click on the link and follow the instructions.

# Return null if you don't need to render anything

If you want to render nothing in the else clause, you can return null.

App.js
export default function App() { const arr = [1, 2, 3, 4, 5, 6]; return ( <div> {arr.map((element, index) => { if (element % 2 === 0) { return <h2 key={index}>{element}</h2>; } // ๐Ÿ‘‡๏ธ Render nothing return null; })} </div> ); }

return null if you dont need to render anything

The example renders the numbers that are divisible by 2, otherwise renders nothing.

Alternatively, you can use a ternary operator.

# Use a condition inside map() using the ternary operator

This is a three-step process:

  1. Call the map() method on an array.
  2. Use a ternary operator to check if the condition is truthy.
  3. The operator returns the value to the left of the colon if the condition is truthy, otherwise, the value to the right is returned.
App.js
export default function App() { const arr = [1, 2, 3, 4, 5, 6]; return ( <div> {arr.map((element, index) => { return element % 2 === 0 ? ( <h2 key={index}>{element}</h2> ) : ( <h2 key={index}>X</h2> ); })} </div> ); }

We used a conditional ternary operator which is very similar to an if/else statement.

If the expression before the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise, the value to the right of the colon is returned.

In other words, if the element is divisible by 2, we return the element, otherwise, return X.

Like in the previous example, if you want to return nothing in the else clause, you have to return null.

App.js
export default function App() { const arr = [1, 2, 3, 4, 5, 6]; return ( <div> {arr.map((element, index) => { return element % 2 === 0 ? <h2 key={index}>{element}</h2> : null; })} </div> ); }

We used the index for the key prop in the examples, however, it's better to use a stable unique identifier if you have one.

The key prop is used internally by React for performance reasons. It helps the library make sure to only re-render the array elements that have changed.

Having said that, you won't see any noticeable difference unless you're dealing with many thousands of array elements.

Make sure you don't have duplicate keys, otherwise, you'll get the Encountered two children with the same key warning.

Note that you shouldn't try to access the key property, otherwise, the warning Key is not a prop. Trying to access it will result in undefined is raised.

# Break a map() loop (map() only part of Array) in React

To break a map() loop:

  1. Call the slice() method on the array to get a portion of the array.
  2. Call the map() method on the portion of the array.
  3. Iterate over the portion of the array.
App.js
export default function App() { const employees = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bob', country: 'Belgium'}, {id: 3, name: 'Carl', country: 'Canada'}, {id: 4, name: 'Delilah', country: 'Denmark'}, {id: 5, name: 'Ethan', country: 'Egypt'}, ]; // ๐Ÿ‘‡๏ธ map() first 2 elements of array return ( <div> {employees.slice(0, 2).map((employee, index) => { return ( <div key={index}> <h2>name: {employee.name}</h2> <h2>country: {employee.country}</h2> <hr /> </div> ); })} </div> ); }

break map loop in react

The Array.slice() method doesn't modify the original array, instead, it creates a new array (a shallow copy of the original array).

We passed the following 2 parameters to the slice() method:

NameDescription
startIndexThe index of the first element to be included in the new array
endIndexGo up to, but not including this index

We specified a start index of 0 and an end index of 2, so we got a portion of the array with elements 0 and 1.

Even if the end index you provide to the Array.slice method exceeds the array's length, the method does not throw an error but returns all array elements.
App.js
const arr = ['a', 'b', 'c']; const first100 = arr.slice(0, 100); console.log(first100); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']

We tried to get the first 100 elements of an array, which only contains 3 elements.

As a result, the new array contains all 3 elements of the original array.

# Map() only a part of an array using filter()

You can also use the Array.filter() method before calling map().

App.js
export default function App() { const employees = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bob', country: 'Belgium'}, {id: 3, name: 'Carl', country: 'Canada'}, {id: 4, name: 'Delilah', country: 'Denmark'}, {id: 5, name: 'Ethan', country: 'Egypt'}, ]; // ๐Ÿ‘‡๏ธ map() LAST 2 elements of array return ( <div> {employees .filter(employee => { return ( employee.country === 'Belgium' || employee.country === 'Denmark' ); }) .map((employee, index) => { return ( <div key={index}> <h2>name: {employee.name}</h2> <h2>country: {employee.country}</h2> <hr /> </div> ); })} </div> ); }

map only part of array using filter

The function we passed to the filter() method gets called with each element in the array.

On each iteration, we check if the current object has a country property equal to Belgium or Denmark and return the result.

The filter() method returns an array containing only the elements for which the callback function returns a truthy value.

In the example, the map() method is only called with the objects with id of 2 and 4.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev