Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add a key prop to a React fragment?

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.

like image 420
sdgfsdh Avatar asked Dec 18 '19 11:12

sdgfsdh


People also ask

Can we give key to fragment?

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.

How do you pass a key as prop React?

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.

Can you add classes to React fragment?

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 .

What are keyed fragments?

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.


1 Answers

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

like image 92
demkovych Avatar answered Sep 25 '22 14:09

demkovych