DEV Community

Samuel Lubliner
Samuel Lubliner

Posted on • Updated on

Navigating Between Pages (Next.js)

You can visit my GitHub repo to follow along with me.

git commit -m "Add link component for client-side navigation"

git commit -m "Add highlighted active link"

Link Component

Traditional <a> HTML elements: full page refresh on each page navigation.

Use Next.js <Link /> Component to link between pages. <Link> facilitates client-side navigation with JavaScript.

In /app/ui/dashboard/nav-links.tsx, import the Link component from next/link. Then, replace the <a href="ā€¦"> tag with <Link href="ā€¦">

Automatic code-splitting and prefetching

Next.js automatically code splits your application by route segments. This is unlike a traditional React SPA, where the browser loads all your application code on initial load.

Splitting code by routes isolate pages. If a certain page throws an error, the rest of the application continues to work.

In production, whenever <Link> components appear in the browser's viewport, Next.js automatically prefetches the code for the linked route in the background. Loading in the background makes the page transition almost instant.

Show active link

Show an active link to the user by getting the user's current path from the URL. The hook called usePathname() can check the path.

Since usePathname() is a hook, turn nav-links.tsx into a Client Component. Add React's "use client" directive to the top of the file, then import usePathname() from next/navigation.

Use the clsx library to conditionally apply class names when the link is active.

Learn more about routing and navigation:
https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works

Top comments (0)