How can you perform client-side routing in Next.js?

clock icon

Asked 1 year ago

message icon

1

eye icon

5

I’m developing a web application using Next.js, and I want to implement client-side navigation between different pages without triggering a full page reload.

I’ve already created some pages inside the /pages directory like index.js, about.js, and contact.js, and I want to navigate between them smoothly — just like a single-page application (SPA).

1 Answer

Basic Usage with next/link

Instead of using a regular HTML <a> tag, wrap it with Next.js's Link component:

1export default function Navbar() {
2 return (
3 <nav>
4 <Link href="/about">
5 <a className="text-blue-600 hover:underline">About</a>
6 </Link>
7 <Link href="/contact">
8 <a className="ml-4 text-blue-600 hover:underline">Contact</a>
9 </Link>
10 </nav>
11 );
12}
13
1export default function Navbar() {
2 return (
3 <nav>
4 <Link href="/about">
5 <a className="text-blue-600 hover:underline">About</a>
6 </Link>
7 <Link href="/contact">
8 <a className="ml-4 text-blue-600 hover:underline">Contact</a>
9 </Link>
10 </nav>
11 );
12}
13

Navigating Programmatically with useRouter()

You can also navigate programmatically using the useRouter hook:

1import { useRouter } from 'next/router';
2
3export default function HomeButton() {
4 const router = useRouter();
5
6 const goToHome = () => {
7 router.push('/');
8 };
9
10 return <button onClick={goToHome}>Go Home</button>;
11}
12
1import { useRouter } from 'next/router';
2
3export default function HomeButton() {
4 const router = useRouter();
5
6 const goToHome = () => {
7 router.push('/');
8 };
9
10 return <button onClick={goToHome}>Go Home</button>;
11}
12

1

Write your answer here

Top Questions