Array map function is not working (not rendering elements in React)

How can I map over array to display all elements from that array?

When I try to render single entry it works but when I map an array it doesn’t do anything.

Below Works:

<h1>{thisSeries[0].productColor}</h1>;

Below does not work:

{thisSeries.map((el) => {
  <h1>PRODUCT: {el.productColor}</h1>;
})}

I have another map in the same render over the same array that works:

<div>
  {thisSeries.length >= 0 &&
    thisSeries.map((el) => (
      <Link
        key={el._id}
        className="link"
        to={`/pr/add/ph/m/p/variant/${el._id}`}
      >
        <button
          style={{ width: "80%" }}
          onClick="window.location.reload();"
        >
          {el.title}
        </button>
      </Link>
    ))}
</div>

Answer

The Array#map method creates a new array populated with the results (i.e. return value) of calling a provided function (i.e. callback) on every element in the calling array.

Here are different ways you can use Array#map:

  1. A named function as callback:
const data = [1,2,3]
data.map(function foo(d) {
  return d*d
})
  1. An anonymous function as callback:
const data = [1,2,3]
data.map(function (d) {
  return d*d
})
  1. An arrow function (using {}) as callback:
const data = [1,2,3]
data.map((d) => {
  return d*d
})
  1. An arrow function as callback:
const data = [1,2,3]
data.map((d) => (d*d))
  1. An arrow function (without {} or ()) as callback:
const data = [1,2,3]
data.map((d) => d*d)

Check Traditional functions vs Arrow functions.

Leave a Reply

Your email address will not be published. Required fields are marked *