Routing in Next.js is straightforward thanks to its file-based routing system and built-in next/link and next/navigation modules. Here’s a guide to help you navigate to other pages in a Next.js application:
Step 1: Setup Pages
In Next.js, any file you add to the pages directory automatically becomes a route. For example, creating about.js inside the pages directory would create a route /about.
Step 2: Navigate Using next/link
Use the next/link component to create navigable links between pages. This component is similar to an anchor (<a>) tag but provides client-side navigation to improve performance.
Example: index.js (Home Page)
import Link from 'next/link';
export default function Home() {
return (
<div>
<h1>Welcome to the Home Page</h1>
<nav>
<ul>
<li>
<Link href="/about">
<a>About</a>
</Link>
</li>
<li>
<Link href="/contact">
<a>Contact</a>
</Link>
</li>
<li>
<Link href="/products">
<a>Products</a>
</Link>
</li>
</ul>
</nav>
</div>
);
}
Step 3: Navigate Programmatically Using next/navigation
Sometimes you may need to navigate programmatically, such as after a form submission. For this, we can use the useRouter hook from next/navigation.
Example: contact.js (Contact Page with Programmatic Navigation)
import { useRouter } from 'next/navigation';
import { useState } from 'react';
export default function Contact() {
const router = useRouter();
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
// Handle form submission logic here
// Navigate to the Thank You page
router.push('/thank-you');
};
return (
<div>
<h1>Contact Us</h1>
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<button type="submit">Submit</button>
</form>
</div>
);
}