I am trying to make an active link and change the styling to underline when it's active. I am using useRouter()
from 'next/navigation', because importing useRouter from 'next/router' gives an error. But my link is still not working.
Here's my code:
import React from 'react';
import Image from 'next/image';
import hamburgerMenu from '../../public/Assets/hamburger-menu.svg';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
function HamburgerMenu({ isModalOpen, handleModal }) {
const { pathname } = useRouter();
return (
<>
{isModalOpen && <></>}
<button onClick={handleModal}>
<Image src={hamburgerMenu} width={20} height={14} />
</button>
{isModalOpen && (
<div className='absolute top-16 left-[50%] translate-x-[-50%]'>
<ul>
<li>
<Link href='/' className={pathname == '/' ? 'underline' : ''}>
Home
</Link>
</li>
<li>
<Link
href='/about'
className={pathname == '/about' ? 'underline' : ''}>
About
</Link>
</li>
</ul>
</div>
)}
</>
);
}
export default HamburgerMenu;
This code is working for everyone except me :(
usePathname
hookAs of Nextjs 13 most of the api has changes include the router APIs.
Now to get the pathName
, you need to use the usePathname
from 'next/navigation'
as shown in the doc:
usePathname
is a Client Component hook that lets you read the current URL's pathname.'use client' import { usePathname } from 'next/navigation' export default function ExampleClientComponent() { const pathname = usePathname() return <>Current pathname: {pathname}</> }
That goes also for accessing search params, 2 new API useSearchParams and useParams.