I am generating a dl
in React:
JavaScript
x
15
15
1
<dl>
2
{
3
highlights.map(highlight => {
4
const count = text.split(highlight).length - 1;
5
6
return (
7
<>
8
<dt key={`dt-${highlight.id}`}>{highlight}</dt>
9
<dd key={`dd-${highlight.id}`}>{count}</dd>
10
</>
11
);
12
})
13
}
14
</dl>
15
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:
JavaScript
1
15
15
1
<dl>
2
{
3
highlights.map(highlight => {
4
const count = text.split(highlight).length - 1;
5
6
return (
7
<div key={highlight.id}>
8
<dt>{highlight}</dt>
9
<dd>{count}</dd>
10
</div>
11
);
12
})
13
}
14
</dl>
15
And I cannot add a key
prop to a fragment (<> </>
).
How can work around this?
I am using React 16.12.0
.
Advertisement
Answer
To add a key to a fragment you need to use full Fragment syntax:
JavaScript
1
4
1
<React.Fragment key={your key}>
2
3
</React.Fragment>
4
See docs here https://reactjs.org/docs/fragments.html#keyed-fragments