How to use if statements within a map callback in React?

Sometimes, we want to use if statements within a map callback in React.

In this article, we’ll look at how to use if statements within a map callback in React.

How to use if statements within a map callback in React?

To use if statements within a map callback in React, we can put the if statements inside the map callback and return the items we want according to the given condition.

For instance, we write:

import React from "react";

const nums = [1, 2, 3, 4, 5, 6];

export default function App() {
  return (
    <>
      {nums.map((n) => {
        if (n % 2 === 0) {
          return (
            <p key={n} style={{ color: "green" }}>
              {n}
            </p>
          );
        } else {
          return (
            <p key={n} style={{ color: "red" }}>
              {n}
            </p>
          );
        }
      })}
    </>
  );
}

We call nums.map with a callback that checks if n is even with n % 2 === 0.

If it is, we return a p element with green text.

Otherwise, we return a p element with red text.

We set the key element of the component we return to a unique value so React can keep track of the items.

Conclusion

To use if statements within a map callback in React, we can put the if statements inside the map callback and return the items we want according to the given condition.