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
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.
https://github.com/vercel/next.js/discussions/49465
Please also check the above link.
Thanks
I used React’s
useState
anduseEffect
to track the currently active section. Here’s a snippet of what I used:https://cnhdhy.csb.app/ (I’ve coded on codesandbox)