Search code examples
javascriptreactjskeyprop

React is duplicating my object value giving me a Warning: Each child in a list should have a unique "key" prop


Im trying to make a navigation bar for a website and it's giving me the "Warning: Each child in a list should have a unique "key" prop." inside my props.dropList.map I have two files:

  • NavigationItems.js -> where I render my navigation bar
const NavigationItems = () => {
  const projectDropdown = [
    { id: 0, value: "architecture" },
    { id: 1, value: "land" },
    { id: 2, value: "design" },
    { id: 3, value: "list" },
  ];
  const officeDropdown = [
    { id: 4, value: "contact" },
    { id: 5, value: "team" },
  ];

  return (
    <div>
      <ul className={styles.NavigationItems}>
        <NavigationItem
          link={`/projects`}
          name="projects"
          dropList={projectDropdown}
        />
        <NavigationItem link={`/news`} name="news" exact />
        <NavigationItem
          link={`/office`}
          name="office"
          dropList={officeDropdown}
        />
      </ul>
    </div>
  );
};

export default NavigationItems;
  • NavigationItem.js -> where I use the map function
const NavigationItem = (props) => {
  let i = 0;
  return (
    <li className={styles.NavigationItem}>
      <NavLink to={props.link} activeClassName={styles.active}>
        {props.name}
      </NavLink>
      {props.dropList && (
        <div className={styles.DropdownItems}>
          <ul className={styles.DropdownItem}>
            {props.dropList.map((drop) => {
              console.log("i " + i);
              console.log("id " + drop.id);
              console.log("value " + drop.value);
              i++;
              return (
                <li key={drop.id}>
                  <NavLink
                    exact
                    to={`${props.link}/${drop.value}`}
                    activeClassName={styles.active}
                  >
                    {drop.value}
                  </NavLink>
                </li>
              );
            })}
          </ul>
        </div>
      )}
    </li>
  );
};

export default NavigationItem;

So what happens is that the code loops twice duplicating the key values. It should be looping only once. I don't know why it loops twice, I'm only mapping my values once. For reference this is what my console shows when I click my links


Solution

  • So your problem doesn't occure in either of the components you provided, but in your "Land" component. (Check the render method of Land)