skip to Main Content

i am trying to create this to change the status of current while joining the page ..

const navigation = [
{ name: "Dashboard", href: "/dashboard", current: false },
{ name: "Team", href: "/dashboard/team", current: false },
{ name: "Projects", href: "/dashboard/projects", current: false },
{ name: "Applications", href: "/dashboard/applications", current: false },
{ name: "Reports", href: "/dashboard/reports", current: false },
];



for (let i = 0; i < navigation.length; i++) {
if (navigation[i].href === location.pathname) {
navigation[i].current = true;
}
}

This is the error i got

i tried to make it with if condition but it’s so messy code and i tried to include the navigation array in every page and change the object from every page but it mess up there’s two page current state being true in the same time :: note : the code is correct but it gives me error when i try to deploy it in vercel to test it with some people

2

Answers


  1. You are using nextjs, that means the first render will happen on the server not the browser so the location and other browser specific globals such as (window, localStorge) will null, the fix is to make you code run on the browser for that wrap your code in a useEffect

    useEffect(() => {
        for (let i = 0; i < navigation.length; i++) {
            if (navigation[i].href === location.pathname) {
                navigation[i].current = true;
            }
        }   
    }, [])
    
    Login or Signup to reply.
  2. NextJs13

    If you want highlight active navigation item use custom component like this:

    'use client';
    
    /*
      NavLink: The "active" class is added when the href matches the start of the URL pathname,
      use the "exact" property to change it to an exact match with the whole URL pathname.
      https://github.com/dstroot/nextjs-13-example/blob/master/components/NavBar/navlink.tsx
    */
    
    import Link, { LinkProps } from 'next/link';
    import { usePathname } from 'next/navigation';
    import { FC, HTMLProps, RefAttributes } from 'react';
    import cn from 'classnames';
    
    export type NavLinkProps = {
      exact?: boolean;
      children?: React.ReactNode;
    } & LinkProps &
      HTMLProps<HTMLAnchorElement> &
      RefAttributes<HTMLAnchorElement>;
    
    export const NavLink: FC<NavLinkProps> = ({ exact, children, className, ...props }) => {
      const pathname = usePathname();
      const isActive = exact ? pathname === props.href : pathname?.startsWith(props.href);
    
      return (
        <Link className={cn(className, { ['link-active']: isActive })} {...props}>
          {children}
        </Link>
      );
    };
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search