Alyona
Alyona

Reputation: 1792

How to get rid of 'key' error while using map in React?

Everyone know this error: Each child in a list should have a unique "key" prop But what if I have array of strings that I want to render in my paragraph with
at the end?

return(
    <p>
    {array.map(string => {
        return <>{string}<br/></>
    })}
    </p>
)

As you can see I'm literally returning only text with <br/> at the end, I don't have place or need for a key. How can I get rid of this error? Wrapping every phrase in <span> is not an option.

Upvotes: 1

Views: 1943

Answers (2)

Dean James
Dean James

Reputation: 2623

When React renders changes, before pushing changes to the DOM, it uses the virtual DOM to intelligently decide which changes it needs to push to keep things efficient, as DOM manipulation can be an expensive operation.

When rendering a collection of child elements, let's say some <li> elements, React will complain when a unique key prop has not been provided. The reason why it needs this prop is so it can perform the intelligent decision I mentioned above.

Oh and as @JBallin mentioned in the comments, you should define the key prop as a string, as it is not recommended to use the index for it:

return(
  <p>
    {array.map((string, index) => <React.Fragment key={index.toString()}>{string}<br/></React.Fragment>)}
  </p>
);

Upvotes: 1

alefseen
alefseen

Reputation: 196

you can use map index for key of paragraph like this:

return(
    <p>
    {array.map((string,index)=> {
        return <React.fragment key={index}>{string}<br/></React.fragment>
    })}
    </p>
)

Upvotes: 0

Related Questions