1

I'm trying to create a form that contains an object of arrays. I'm getting the error Encountered two children with the same key,1:$[object Object].. How do I create a unique key?

renderPositions() {
  const profileCandidateCollection = this.props.profileCandidate;
  const careerHistoryPositions = profileCandidateCollection && profileCandidateCollection.careerHistoryPositions;

  if (careerHistoryPositions) {
    return careerHistoryPositions.map((key, position) => {
      return (
        <CareerHistoryPositionsUpdateForm
          key={key}
          company={position.company}
          title={position.title}
        />
      )
    })
  }
}

1 Answer 1

3

You're almost correct. If you want to use the index in map the element comes first and the index goes second:

return careerHistoryPositions.map((position, key) => {
   return (
     <CareerHistoryPositionsUpdateForm
       key={key}
       company={position.company}
       title={position.title}
     />
   )
})

The index works for keys but in React it's discouraged. Instead, use a unique identifier:

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:

So for each item that gets added to careerHistoryPositions add another key with a unique ID and use that as the list key. In the past, I've used the v4 method from the UUID package to create unique ID's.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I did read that in the React docs. Your suggestion to create a unique Id for each object is a good idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.