Home > Mobile >  ERR : Warning: Each child in a list should have a unique "key" prop
ERR : Warning: Each child in a list should have a unique "key" prop

Time:12-24

Then I used the map and I encountered the error "Each child in a list should have a unique "key" prop.".

This warning pops for me every time and I can't find the error.

import React from "react";
import { NavLink } from "react-router-dom";

const NavLink = () => {
  const LINKS = [
    {
      path: "/",
      name: "Home",
    },
    {
      path: "/search",
      name: "Search",
    },
    {
      path: "/",
      name: "Home",
    },
  ];
  return (
    
      <>
        {LINKS.map((link, index) => {
          <NavLink
            className={({ isActive }) =>
              "text-xs mr-8 "   (isActive ? " text-yellow" : "text-dark")
            }
            to={link.path}
            key={`${link.name}-${index}`}
          >
            {link.name}
          </NavLink>;
        })}
      </>

     
  );
};

export default NavLink;

CodePudding user response:

You need to add key prop to a unique number to NavLink component.

Here is the code

import React from "react";
import { NavLink } from "react-router-dom";

const NavLinkComponent = () => {
  const LINKS = [
    {
      id : 1,
      path: "/",
      name: "Home",
    },
    {
      id:2,
      path: "/search",
      name: "Search",
    },
    {
      id :3,
      path: "/",
      name: "Home",
    },
  ];
  return (
    
      <>
        {LINKS.map((link) => {
          <NavLink
            key={link.id}
            className={({ isActive }) =>
              "text-xs mr-8 "   (isActive ? " text-yellow" : "text-dark")
            }
            to={link.path}
            key={`${link.name}-${index}`}
          >
            {link.name}
          </NavLink>;
        })}
      </>

     
  );
};

export default NavLinkComponent;

This is the best practice to follow.

CodePudding user response:

From what I can see your only mistake is that you used wrong brackets, instead of curly brackets you should use normal ones to instantly return jsx inside of a map function you have here. You should do this:

<>
        {LINKS.map((link, index) => (
          <NavLink
            className={({ isActive }) =>
              "text-xs mr-8 "   (isActive ? " text-yellow" : "text-dark")
            }
            to={link.path}
            key={`${link.name}-${index}`}
          >
            {link.name}
          </NavLink>;
        ))}
      </>

This is normal JavaScript syntax where you can instantly return something from a function by using normal brackets, example:

Default return

const normalReturn = () => {
return 2 2
}

Return using normal brackets :

const quickReturn = () => (
2 2
)

Using this is a standard in JSX so you should stick to that. And for key props you can just use index that you get from map function.

  • Related