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
.
Fragments can have key props! To specify a key for a fragment, you'll need to use the standard JSX element syntax; you can't use the new <></> syntax. Why would you want to give a Fragment a key? Well, it allows fragments to be used as items in arrays.
If you want to pass the id to the component so that it can access it, choose a different prop name. You have to set key as well: <FeedItem key={item.id} id={item.id} /> . It may seem redundant, but they serve different purposes: key is for React and id is for your component.
If you need to add a className there, it's clear that either you add a dom element in this case another div or add the className to its parent. Show activity on this post. Using Fragment means not adding an extra node to DOM. If you want to assign a className to a node then you'll have to use div .
A use case for keyed fragments is mapping a collection to an array of fragments. Fragments declared with the explicit <React. Fragment> syntax may have keys.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With