-2

Consider the following:

I'm looping through an array of objects for my nav in my Next.js app, however I added the key prop to the children of the <ul> i.e. <li> and I am still getting the error?? What am I missing?

  const nav = [
    { id: 1, route: '/', name: 'Home' },
    { id: 2, route: '/profile', name: 'Profile' },
    { id: 3, route: '/dashboard', name: 'Dashboard' },
    { id: 4, route: '/logout', name: 'Logout' },
    { id: 5, route: '/login', name: 'Login' },
    { id: 6, route: '/registration', name: 'Registration' }
  ];

  function LogOutAnchor({ route, name, isMobile }) {
    if (route === '/logout' && isMobile) {
      console.log('foo')
      return (<li>
        <Link
          href={route}
          key={route.id}
        ><a
          role="button"
          onClick={() => { uidispatch({ type: 'showModal' }); handleClickOnInput() }}
        >{name}</a>
        </Link>
      </li>)
    } else if (route !== '/logout' && isMobile) {
      return (
        <li>
          <Link
            href={route}
            key={route.id}
          >
            <a
              role="button"
              onClick={() => { handleClickOnInput() }}
            >{name}</a>
          </Link>
        </li>)
    }
    else if (route == '/logout' && !isMobile) {
      return (
        <li>
          <Link
            href={route}
            key={route.id}
          >
            <a
              role="button"
              onClick={() => uidispatch({ type: 'showModal' })}
            >{name}</a></Link></li>)
    }
    else if (route != '/logout' && !isMobile) {
      return (<li>
        <Link
          href={route}
          key={route.id}
        ><a >{name}</a>
        </Link>
      </li>)
    }
  }

       <ul className={mobile ? "p-4 overflow-y-auto menu w-80 bg-base-100" : "menu horizontal"}>
          {
            nav.map(({ route, name }) => (
              <>
                {
                  user && user.isVerified ?
                    ((route === '/login') || route === '/registration') ? null :
                      <LogOutAnchor route={route} name={name} isMobile={mobile} />
                    :
                    ((route === '/profile') || route === '/dashboard' || route === '/logout') ? null :
                      <LogOutAnchor route={route} name={name} isMobile={mobile} />
                }
              </>
            ))
          }
        </ul>
Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141

1 Answers1

2

You should add the key={} property to the top most element inside of any loop. In this case, it would be your LogOUtAnchor components.

Change this:

<LogOutAnchor route={route} name={name} isMobile={mobile} />

To this:

<LogOutAnchor key={route.id} route={route} name={name} isMobile={mobile} />
gunwin
  • 4,578
  • 5
  • 37
  • 59