skip to Main Content

I have a navbar with some Link pointing to other pages and other Links pointing to sections of pages

I want to know which section is currently active. I tried the usePathname as suggested in the docuemntation but this only shows the activa page not the section within the page:

import { usePathname} from 'next/navigation';

const NavBar = () => {
  const pathname = usePathname();  

  const isActive = (href) => {
    console.log(pathname)
    console.log(href)
    if (pathname.startsWith(href)) {
        return " text-orange-500 animation-active ";
    }
    return " text-black-500 hover:text-orange-500 ";
};

The logging above always show:

/
/#about
/
/#contact

so pathname is always the global page. in this case homepage /. but Even when I click on the sections, the pathname does not change event though the url itself changes.

How can I get the active section within a page?

2

Answers


  1. Use useRouter from next/router in Next.js for internal links with hash fragments to access the full path, including the hash, as usePathname from next/navigation only provides the current pathname without the hash.

    import { useRouter } from 'next/router';
    
    const NavBar = () => {
      const { asPath } = useRouter();
    
      const isActive = (href) => {
        if (asPath.startsWith(href)) {
          return "text-orange-500 animation-active";
        }
        return "text-black-500 hover:text-orange-500";
      };
    }
    

    https://github.com/vercel/next.js/discussions/49465

    Please also check the above link.

    Thanks

    Login or Signup to reply.
  2. I used React’s useState and useEffect to track the currently active section. Here’s a snippet of what I used:

    const [activeSection, setActiveSection] = useState('');
    
    useEffect(() => {
      const handleHashChange = () => {
        setActiveSection(window.location.hash);
      };
    
      window.addEventListener('hashchange', handleHashChange);
      handleHashChange();
    
      return () => {
        window.removeEventListener('hashchange', handleHashChange);
      };
    }, []);
    

    https://cnhdhy.csb.app/ (I’ve coded on codesandbox)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search