Home > database >  react typescript key property not show in the render page
react typescript key property not show in the render page

Time:07-25

I am using typescript react and got the error message as

react-jsx-dev-runtime.development.js:87 Warning: Each child in a list should have a unique "key" prop.

However I do have key in the li tag as :

const MyMenuItem:React.FC<MenuItem> =({title, link, cls}) => {
  return (
    <li className="list-group-item" key={title}>
        <Link to={link} className={cls}>
          {title}
        </Link>
    </li>
  )
}

I checked the rendered element. in the li section, the key disappeared. Not sure how it happen. Why key disappeared.

CodePudding user response:

You might have the index to be the key. So that it has the only key

CodePudding user response:

Key should be unique, so maybe title is not unique. Also key should not be put inside the child component instead should be on the component you are rendering in a list.

E.g.

   <>
    {items.map((item) => <MyMenuItem key={item.id} />)}
   </>

Or if you don't have a usable unique id you can also use index

   <>
    {items.map((item, idx) => <MyMenuItem key={idx} />)}
   </> 
  • Related