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

Time:10-29

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?

CodePudding user response:

keys are not rendered in actual dom. The reason you're getting that error is that you didn't pass the key to MyComponent So it should be something like this.

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

Make sure keys are not duplicated.

You can also pass index like this to avoid any duplicate.

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

CodePudding user response:

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} />
))}
  • Related