Using routing in Next.js is a very powerful and user-friendly method for managing application paths. Overall, Next.js leverages filesystem routing, allowing you to add new files to the pages
directory to create different pages effortlessly. If you have worked with other frameworks, you will notice that this capability is one of the simplest ways to build structured applications.
In this method, every new file created within the pages
directory is automatically converted into a route in the application. This feature helps you implement processes without the need for specific changes to the configuration file or using additional libraries, simplifying path management.
For example, if you create a file named about.js
in the pages
directory, you can access it via the path /about
. This method includes creating an automatically generated routing system that makes the development experience very easy and user-friendly.
Similarly, Next.js supports dynamic routing, allowing you to create paths like /users/[id]
. This feature is extremely useful for creating personalized or user profile pages. All these capabilities together enable Next.js to be a highly suitable tool for creating varied and complex web applications.
Utilizing these functionalities helps you develop more expediently and manage intricate applications more easily. Now let's look at a practical example that illustrates this concept.
A Simple Example of Routing in Next.js
// File pages/about.js
import React from 'react';
function About() {
return (
<div>
<h1>About Page</h1>
<p>Welcome to the about page.</p>
</div>
);
}
export default About;
// File pages/users/[id].js
import React from 'react';
import { useRouter } from 'next/router';
function User() {
const router = useRouter();
const { id } = router.query;
return (
<div>
<h1>User Profile: {id}</h1>
</div>
);
}
export default User;
Line-by-Line Explanation of the Code
// File pages/about.js
This code creates a simple page named "About" that is accessible at the path
/about
.import React from 'react';
This line imports the React module for use in the component.
function About() { ... }
This defines a functional component named About.
return (<div> ... </div>);
The content of the "About" page includes a title and a welcome message.
export default About;
This exports the About component as the default export.
// File pages/users/[id].js
This file creates a dynamic route for displaying user profiles.
import { useRouter } from 'next/router';
This imports the
useRouter
hook for use in the component.const router = useRouter();
This line uses the hook to get the router object.
const { id } = router.query;
This extracts the
id
parameter from the router's query for display in the page.return (<div> ... </div>);
This renders the user profile content based on the
id
in the URL.export default User;
This exports the User component as the default export.