Next.js provides a powerful and intuitive file-based routing system, where the structure of your files within the pages
directory directly determines the routes in your application. This system, combined with programmatic navigation and query parameters, makes it easy to manage routing within your Next.js projects.
Overview
Concepts we'll cover:
- File-Based Routing: How Next.js automatically generates routes based on the file structure in the
pages
directory. - Programmatic Navigation with
useRouter
: How to navigate between pages programmatically using theuseRouter
hook. - Linking with the
Link
Component: How to link between pages using theLink
component provided by Next.js. - Passing and Accessing Query Parameters: How to pass query parameters in the URL and access them on the target page.
Step-by-Step Implementation
1. Understanding File-Based Routing in Next.js
In Next.js, the routing is automatically handled by the framework based on the files in the pages
directory. Each file in this directory corresponds to a route in your application.
File Structure:
pages/
|-- index.js // Corresponds to '/'
|-- about.js // Corresponds to '/about'
|-- blog/
| |-- [id].js // Dynamic route: '/blog/:id'
|-- contact.js // Corresponds to '/contact'
Explanation:
index.js
: This file corresponds to the home route (/
).about.js
: This file corresponds to the/about
route.- Dynamic Routes: Files with square brackets, like
[id].js
, create dynamic routes. For example,blog/[id].js
would match routes like/blog/1
or/blog/hello-world
.
2. Navigating Programmatically with useRouter
Next.js provides the useRouter
hook for programmatic navigation. This hook gives you access to the router object, allowing you to navigate between pages, push new routes, and manipulate the history stack.
Example:
File: pages/index.js
import { useRouter } from 'next/router';
export default function Home() {
const router = useRouter();
const goToAboutPage = () => {
router.push('/about');
};
const goToBlogPost = (id) => {
router.push(`/blog/${id}`);
};
return (
<div>
<h1>Home Page</h1>
<button onClick={goToAboutPage}>Go to About Page</button>
<button onClick={() => goToBlogPost(1)}>Go to Blog Post 1</button>
</div>
);
}
Explanation:
useRouter
Hook:router.push('/about')
navigates the user to the/about
page.router.push('/blog/1')
navigates to a dynamic route, such as/blog/1
.
3. Linking Between Pages with the Link
Component
Next.js also provides a Link
component that allows for client-side transitions between routes. This component enhances the standard anchor tag (<a>
) by enabling faster navigation without full page reloads.
Example:
File: pages/index.js
import Link from 'next/link';
export default function Home() {
return (
<div>
<h1>Home Page</h1>
<Link href="/about">
<a>Go to About Page</a>
</Link>
<Link href="/blog/2">
<a>Go to Blog Post 2</a>
</Link>
</div>
);
}
Explanation:
Link
Component:- The
Link
component wraps an anchor tag, enabling client-side navigation. href="/about"
specifies the route to navigate to.- Inside the
Link
component, you must use an<a>
tag to define the clickable area.
- The
4. Passing and Accessing Query Parameters
You can pass query parameters in the URL and access them in the target component using the useRouter
hook.
Example:
File: pages/blog/[id].js
import { useRouter } from 'next/router';
export default function BlogPost() {
const router = useRouter();
const { id } = router.query;
return (
<div>
<h1>Blog Post {id}</h1>
<p>This is the content for blog post {id}.</p>
</div>
);
}
Explanation:
- Dynamic Route: The file
[id].js
allows for dynamic routing based on theid
parameter. - Accessing Query Parameters:
const { id } = router.query;
extracts theid
from the URL, making it accessible within the component.- If you navigate to
/blog/2
,id
will be2
.
Conclusion
Next.js makes routing straightforward with its file-based routing system. By placing files in the pages
directory, you automatically create routes without needing additional configuration. Combined with the useRouter
hook and the Link
component, navigating between pages programmatically or via links is simple and powerful.
Key Points:
- File-Based Routing: Next.js uses the file structure under the
pages
directory to determine the routes in your application. - Programmatic Navigation: The
useRouter
hook allows for navigating between pages programmatically, perfect for scenarios like form submissions or event handling. - Client-Side Navigation: The
Link
component enables faster client-side navigation without full page reloads. - Query Parameters: You can pass and access query parameters using dynamic routes and the
useRouter
hook.