Search code examples
reactjscomponentskeywarnings

React removes key from my div and then throws error because of that


I have a react func component that is simly returns this:

<div name={id} key={id}>{id}</div>

Problem I have is that when I use this component like so:

{Object.keys(data).map(key => (
    <MyComponent id={key} data={data[key]} />
))}

I get error Warning: Each child in a list should have a unique "key" prop. and when I look at generated html it has no key.

<div name="7987">7987</div>
<div name="21727">21727</div>
<div name="157119">157119</div>
<div name="232881">232881</div>

So the question is why is key removed and warning as error is generated?


Solution

  • the react compiler wants the key prop in

    <MyComponent id={key} data={data[key]} />
    

    rather than

    <div name={id} key={id}>{id}</div>
    

    one way to avoid this is

    <MyComponent id={key} data={data[key]} key={key} />
    

    or to make sure there are no duplicate keys

    {Object.keys(data).map((key, index) => (
    <MyComponent id={key} data={data[key]} key={index} />
    ))}