JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Using conditions to jump out of a map in map() in React

Author:JIYIK Last Updated:2025/03/03 Views:

Using conditions in map() in React:

  1. Calls the method on the array map().
  2. Use ifa condition to explicitly return if the condition is met.
  3. Otherwise return a different value or return nullto render nothing.
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>
  );
}

We Array.mapiterate over an array using the method.

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

In each iteration, we check if the element is divisible by 2, if so, we return the element, otherwise, we return X.


If you don't need to render anything, return null

If you don't want to render anything in the else clause, you can return null.

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>
  );
}

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

Alternatively, we can use the ternary operator.

Using ternary operator with conditions in map()

This is a three-step process:

  1. Calls the method on the array map().
  2. Use the ternary operator to check if a condition is true.
  3. The operator returns the value on the left of the colon if the condition is true, otherwise it returns the value on the right.
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 if/elsea conditional ternary operator very similar to the statement.

If the expression before the question mark evaluates to true, then 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 we return X.

As in the previous example, if you want to return nothing in the else clause, you must return null.

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 an index for the key prop in our examples, however, it is better to use a stable unique identifier if available.

React uses the key prop internally for performance reasons. It helps the library ensure that only changed array elements are re-rendered.

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

Breaking out of map() loops in React (map() is just a slice of an array)

To break out of the map() loop:

  1. Call the slice() method on an array to get a portion of the array.
  2. Calls the map() method on a portion of an array.
  3. Iterate over a portion of an array.
export default function App() {
  const employees = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Jiyik', country: 'China'},
    {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>
  );
}

Array.slicemethod does not modify the original array, but creates a new array (a shallow copy of the original array).

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

  • startIndex The index of the first element to be included in the new array
  • endIndex up, but not including this index

We specified a starting index of 0 and an ending index of 2, so we get the portion of the array that contains elements 0 and 1.

Even if the end index we provide to Array.slicethe method exceeds the length of the array, the method will not throw an error but return all the array elements.

const arr = ['a', 'b', 'c'];

const first100 = arr.slice(0, 100);
console.log(first100); // 👉️ ['a', 'b', 'c']

We are trying to get the first 100 elements of an array which contains only 3 elements.

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


Map() is just a part of the array, use filter()

We can also map()use Array.filterthe method before calling .

export default function App() {
  const employees = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Jiyik', country: 'China'},
    {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>
  );
}

The function we pass to filter()the method is called for each element in the array.

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

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

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

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to avoid cross-origin (CORS) issues in React/Next.js

Publish Date:2025/03/17 Views:170 Category:NETWORK

In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:188 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:187 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:102 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:60 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:191 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial