skip to Main Content

I have an array of data:

const arr = [
  {
    title: "title1",
    content: [
      {
        id: "home",
        name: "Home",
      },
      {
        id: "services",
        name: "services",
      },
      {
        id: "Appointments",
        name: "Appointments",
      },
    ],
  },
  {
    title: "title2",
    content: [
      {
        id: "about us",
        name: "about us",
      },
      {
        id: "contact",
        name: "contact",
      },
      {
        id: "blog",
        name: "blog",
      },
    ],
  },
];

I want to map through all of it.
I’ve tried using nested maps and adding key prop to each tag

{arr.map((element) => (
          <div key={element.name}>
            <h4 key={element.name}>{element.title}</h4>
            <ul key={element.name}>
              {element.content.map((index) => (
                <li key={index.id}>
                  {index.name}
                </li>
              ))}
            </ul>
          </div>
        ))}

I’ve tried using nested maps and it works fine and shows the array but I got this warning

Warning: Each child in a list should have a unique "key" prop.

How should I solve this warning?

2

Answers


  1. {arr.map((element , index) => (     // added index 
          <div key={index}>
            <h4 key={element.name}>{element.title}</h4>
            <ul key={element.name}>
              {element.content.map((index) => (
                <li key={index.id}>
                  {index.name}
                </li>
              ))}
            </ul>
          </div>
        ))}
    

    This Adds index to array map.

    Login or Signup to reply.
  2. When any loop or nested loop begins key={index} should be placed in the parent element tag.
    It should work:

    {arr.map((element,index) => (
              <div key={index}>
                <h4>{element.title}</h4>
                <ul>
                  {element.content.map((item,index2) => (
                    <li key={index2}>
                      {item.name}
                    </li>
                  ))}
                </ul>
              </div>
            ))}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search