HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

Can I add a key prop to a React fragment?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fragmentpropkeyreactaddcan

Problem

I am generating a dl in React:

{
highlights.map(highlight => {
const count = text.split(highlight).length - 1;

return (
<>
{highlight}
{count}

);
})
}



This gives me the warning:

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

This will remove the warning, but doesn't generate the HTML I want:

{
highlights.map(highlight => {
const count = text.split(highlight).length - 1;

return (

{highlight}
{count}

);
})
}



And I cannot add a key prop to a fragment (<> ).

How can work around this?

I am using React 16.12.0.

Solution

To add a key to a fragment you need to use full Fragment syntax:


...


See docs here https://reactjs.org/docs/fragments.html#keyed-fragments

Code Snippets

<React.Fragment key={your key}>
...
</React.Fragment>

Context

Stack Overflow Q#59390955, score: 574

Revisions (0)

No revisions yet.