Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  37] [ 5]  / answers: 1 / hits: 58919  / 5 Years ago, wed, december 18, 2019, 12:00:00

I am generating a dl in React:


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

return (
<>
<dt key={`dt-${highlight.id}`}>{highlight}</dt>
<dd key={`dd-${highlight.id}`}>{count}</dd>
</>
);
})
}
</dl>

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:


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

return (
<div key={highlight.id}>
<dt>{highlight}</dt>
<dd>{count}</dd>
</div>
);
})
}
</dl>

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


How can work around this?




I am using React 16.12.0.


More From » reactjs

 Answers
11

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



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


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


[#51378] Wednesday, December 4, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranavrorys

Total Points: 466
Total Questions: 87
Total Answers: 115

Location: Barbados
Member since Sun, Nov 27, 2022
2 Years ago
pranavrorys questions
Fri, May 27, 22, 00:00, 2 Years ago
Thu, Oct 28, 21, 00:00, 3 Years ago
Sat, May 30, 20, 00:00, 4 Years ago
Fri, Dec 20, 19, 00:00, 5 Years ago
;