1

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.

Alyona
  • 1,682
  • 2
  • 21
  • 44
  • This might be an xy problem. Why are you using `
    ` here? Depending on what you're doing, maybe drop the `p` and use a `ul` or `li` which is the correct semantic for lists of items. See [this](https://stackoverflow.com/questions/1726073/is-it-sometimes-bad-to-use-br#:~:text=The%20main%20reason%20for%20not,space%20the%20blocks%20out%20properly.)
    – ggorlen Dec 03 '20 at 22:39
  • I actually don't need list. I have a normal paragraph, that I get from server as array, each element means that new line supposed to be there, therefore `
    `. I don't want react to listen to it, since I'm literally printing several lines into same paragraph.
    – Alyona Dec 04 '20 at 07:55

2 Answers2

1

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>
);
Dean James
  • 2,491
  • 4
  • 21
  • 29
0

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>
)
alefseen
  • 176
  • 6
  • 1
    Note that React [doesn't recommend](https://reactjs.org/docs/lists-and-keys.html) using indices for keys. – JBallin Dec 03 '20 at 22:46
  • if your data haven't an unique key you must use map index or generate id for every items! – alefseen Dec 03 '20 at 22:52
  • You might want to be careful when trying to "...generate id for every items". Every time a re-render is about to occur and a new set of keys are used, React doesn't know to optimise. It's best to use strings that don't change to leverage performance optimisation during DOM diffing. – John Otu Mar 24 '23 at 08:53