Use the map() function in React to display items in DOM

We have an array of objects called cats. We want to display the cats' names as an unordered list in the DOM.

import React from "react";

function App() {
  const cats = [
    { name: "Nanny" },
    { name: "Minki" },
    { name: "Bread" },
    { name: "TinkerBell" },
    { name: "Jam" },
  ];

  return (
    <div className="App">
      <ul>
        {cats.map((cat) => (
          <li>{cat.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

The result in my application will be a basic list displaying the names of the cats.

image.png

However, in my console is an error, asking for the unique "key" prop.

image.png

This is an easy fix. Add a key in the html to the mapped item.

return (
    <div className="App">
      <ul>
        {cats.map((cat) => (
          <li key={cat.name}>{cat.name}</li>
        ))}
      </ul>
    </div>
  );

The final code will look like this:

import React from "react";

function App() {
  const cats = [
    { name: "Nanny" },
    { name: "Minki" },
    { name: "Bread" },
    { name: "TinkerBell" },
    { name: "Jam" },
  ];

  return (
    <div className="App">
      <ul>
        {cats.map((cat) => (
          <li key={cat.name}>{cat.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;