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>

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply