1

I'm trying to simply show an active link in header navigation. In next < 13 I was using useRoute(). However, useRoute() is not working in 13+. Another problem is that useRoute is not mounted if you are using SSR.

So, my workaround was to make sure, that global layout is client-side component. Global layout:

'use client';

import * as React from 'react';
import {Footer, Header, Sidebar} from '../components';

import '../styles/globals.css';

export default function RootLayout({children}: {children: React.ReactNode}) {
    return <html>
        <body>
            <div className='wrapper'>
                <Header pathname={window ? window.location.pathname : ''}/>
                <Sidebar/>
                <>
                    {children}
                </>
                <Footer />
            </div>
        </body>
    </html>
}

The nav condition:

<nav className={styles.navigation}>
    <ul>
                {URL.map(route => <li key={route.path}>
                    <Link
                        className={route.path === pathname ? styles.highlighted : ''}
                        href={route.path}
                    >
                        {route.name}
                    </Link>
                </li>)}
    </ul>
</nav>

But it doesn't work correctly, and the url is active only after the page refresh. No props inside pages or layouts could give me the desired behaviour.

I would assume this is something simple, but I struggle to find how to do that both on client side and with SSR.

Thank you in advance.

Animus
  • 665
  • 12
  • 24

1 Answers1

2

you can use usePathname which can be used client side only.

This hook is not available in Server Components. It does not accept any arguments.

here is how, in Header component remove the pathname prop and do this:

"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";

export default function Header() {
  const pathname = usePathname();

  return (
    <nav className="nav">
      {URL.map((route, index) => (
        <Link
          key={index}
          href={route.path}
          className={route.path === pathname ? styles.highlighted : '' }
        >
          {route.name}
        </Link>
      ))}
    </nav>
  );
}

you can see a working example here Edit reverent-pateu-2w1d9b

mocherfaoui
  • 902
  • 1
  • 2
  • 11