Home > other >  Each child in a list should have a unique "key" prop. Even after assigning the key (Next J
Each child in a list should have a unique "key" prop. Even after assigning the key (Next J

Time:11-03

I'm using Next JS. I've created a sidebar and added custom accordions (I've named the accordion component as SideAccord.js) in it. I'm looping the data through array. I've assigned the key but I'm still getting this error:

Warning: Each child in a list should have a unique "key" prop.

Check the render method of SideAccord. See https://reactjs.org/link/warning-keys for more information.
at SideAccord (webpack-internal:///./components/SideAccord/index.js:25:19)
at ul
at div
at div
at nav
at div
at O (webpack-internal:///./node_modules/styled-components/dist/styled-components.browser.esm.js:31:19750)
at Sidebar (webpack-internal:///./components/Sidebar/index.js:28:66)
at div
at Home
at MyApp (webpack-internal:///./pages/_app.js:18:24)

You can check the files here - - enter image description here

CodePudding user response:

I opened the sandbox, code is not running. anyway i saw your code and here's my give

  1. outer most element that you return from map method should have key. You are using <></> but it doesn't have key. Try <React.Fragment key={i.id}...</React.Fragment>
  2. you have using same id 1, 2, 3, ... on two different array so if you use those id on two place then it's not unique, use UUID or similar

CodePudding user response:

TLDR: update <> wrapper in item.subNav.map in SideAccord to:

<React.Fragment key={i.id}>

Relevant code in SideAccord.js:

item.subNav.map((i, index) => {
  return (
    <>
      <DevNavAccordianSectionItem key={i.id}>
        ...
      </DevNavAccordianSectionItem>
    </>
  );
});

The key needs to be set on the parent component (<>), whereas currently you have it set on the first child (DevNavAccordianSectionItem).

<> is shorthand for React.Fragment, which only supports the key prop when used in the expanded form (<React.Fragment /> or <Fragment /> if you import { Fragment } from react).

Btw, you likely don't need to set the key on DevNavAccordianSectionItem.

CodePudding user response:

You need to use the key attribute on the parent block. In Your code it is <> </>. But <> </> can't have any attribute. So, you need to update them with <React.Fragment><\React.Fragment> and also put the key attribute there.

item.subNav.map((i, index) => {
  return (
    <React.Fragment key={i.id}>
      <DevNavAccordianSectionItem>
        <DevNavAccordianSectionTitle href={`${i.path}`}>
          <DevNavAccordianSectionText>
            {i.title}
          </DevNavAccordianSectionText>
        </DevNavAccordianSectionTitle>
      </DevNavAccordianSectionItem>
    </React.Fragment>
  );
})}

Update your code here (From line 34-47): https://codesandbox.io/s/festive-turing-59uo4v?file=/src/SideAccord.js:1168-1756

  • Related