1

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 :(

0

1 Answer 1

3

usePathname hook

As 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}</>
}    

Aside

That goes also for accessing search params, 2 new API useSearchParams and useParams.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.