Home > Net >  Each child in a list should have a unique "key" prop. I made it, but still see this error
Each child in a list should have a unique "key" prop. I made it, but still see this error

Time:06-15

I know about key prop, so i made it in listitem component

const ListItem = ({item}) => {
const {result, time, id} = item;
return(
    <li key={id} className='list__item'>
        <span className='item__result'>{result} cps</span>
        <span className='item__date'>{time}</span>
        <button className='item__delete'>delete</button>
    </li>
)}

And here is component, where I use it

const Leadboard = () => {
const [data, setData] = useState([{result:'5,63', time:'08.06.2022', id:  (new Date()).toString(16)}, {result:'5,63', time:'08.06.2022', id:  (new Date() - 1)}, {result:'5,63', time:'08.06.2022', id:  (new Date() - 2)}]);

let elements=data.map(item => {
    return (
        <>
            <ListItem item={item} />
        </>
    )
});

return(
    <div className='app-leadboard'>
        <span className='app-leadboard__title'>Your's best results:</span>
        <ol className='app-leadboard__list' type='1'>
            {elements}
        </ol>
    </div>
)}

But after render I still see "key prop" error

I spent so much time on this, but can't understand what's wrong. So smb, help pls with it

CodePudding user response:

You’ve got the wrong list. It’s the <ListItem> components that need the key. (And you can get rid of the react fragments around them because they are pointless).

CodePudding user response:

React first accesses the empty bracket (<> </> ) before accessing the key attribute in your child component.

So you need to either

  1. Make use of the empty brackets and pass the key attribute to it
// Use React.Fragment 

  let elements=data.map(item => { return 
  (
   <React.Fragment key={item.id}>
 <ListItem item={item} />
</React.Fragment>
)
});

and remove the key in the child (ListItem) component

ListItem.js
 <li 
 /*  Remove this
key={id} 
*/

  className='list__item'>

OR

Get rid of the empty brackets (<> </>) and reference the child's component directly.

let elements=data.map(item => {
return (<ListItem item={item} />)
});

and leave the key attribute in the child component

More on React Fragment. React Official Docs

  • Related