skip to Main Content

I am trying to fetch information from my mongodb server and display it using map.

<div>
  <h1>Mypolls</h1>
  {/* You can map through the polls array and render the poll data */}
  {polls.map((poll) => (
    <div key={poll.id}>
      <div>{poll.question}</div>
      {/* Map through options and render each option */}
      {poll.options.map((option, index) => (
        <div key={`${poll.id}-${index}`}>{option.text}</div>
      ))}
    </div>
  ))}
</div>

Question is being displayed but options are not.

Console is showing the following error:
"Warning: Each child in a list should have a unique "key" prop."

2

Answers


  1. It seems like you’re correctly assigning a unique key to each poll element, but the issue might be with the key for the options within each poll. The key should be unique for each element in the array, but currently, you are using the same key for each option in every poll.

    To fix this issue, you can combine the poll id with the index of the option to create a unique key for each option. Update the key for options like this:

    {poll.options.map((option, index) => (
    <div key={${poll.id}-${index}}>{option.text}
    ))}

    Login or Signup to reply.
  2. You’ve correctly assigned a unique key to the outer element inside the first map function using key={poll.id}, but you also need to assign a unique key to each inner element inside the second map function. The error you’re seeing indicates that the inner elements inside the second map function are missing unique keys.

    To fix this issue, you can use a combination of the poll id and the index of the outer map function to create unique keys for the inner elements. Here’s an updated version of your code:

    <div>
      <h1>Mypolls</h1>
      {/* You can map through the polls array and render the poll data */}
      {polls.map((poll, pollIndex) => (
        <div key={pollIndex}>
          <div>{poll.question}</div>
          {/* Map through options and render each option */}
          {poll.options.map((option, optionIndex) => (
            <div key={`${pollIndex}-${optionIndex}`}>{option.text}</div>
          ))}
        </div>
      ))}
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search