Adding a New Page (Routes in Next.js)
Next.js offers a powerful file-based routing system that makes it straightforward to add new routes to your application. Follow these steps to add a new route in Next.js:
1. Create a New File in the pages Directory
Next.js uses the pages directory to create routes based on file names automatically.
1.1 Navigate to the pages directory in your project.
1.2 Create a new file with a .js, .jsx, .ts, or .tsx extension. The file name will determine the route path. For example, creating a file named about.js will create a route at /about.
2. Add a React Component to the New Page File
2.1 Open your new file (e.g., about.js).
2.2 Add a React component that will be rendered when the route is accessed.
Example about.js:
const About = () => {
return (
<div>
<h1>About Us</h1>
<p>This is the about page of our website.</p>
</div>
);
};
export default About;
3. Add Nested Routes
To create nested routes, organize files in subdirectories within the pages directory. Each subdirectory and file will correspond to the URL path.
Example:
mkdir pages/products
touch pages/products/index.js
touch pages/products/[id].js
-
pages/products/index.jswill be available at/products. -
pages/products/[id].jswill create dynamic routes based on theidparameter. Dynamic routes are defined by square brackets in the file name. For example,pages/product/[id].jscreates a route with a dynamic segment (/product/1,/product/2, etc.).
Example pages/products/[id].js:
import { useRouter } from 'next/router';
const Product = () => {
const router = useRouter();
const { id } = router.query;
return (
<div>
<h1>Product {id}</h1>
<p>This is the page for product {id}.</p>
</div>
);
};
export default Product;
4. Add a Link to the New Page
To navigate to your new page from within the application, use the Link component from next/link.
Example:
import Link from 'next/link';
const HomePage = () => {
return (
<div>
<h1>Product List</h1>
<Link href="/pages/products">
<a>Go to Product List</a>
</Link>
</div>
);
};
export default HomePage;
Documentation Reference for Next.js Routing
For more detailed information on Next.js routing, refer to the official Next.js documentation:
If you face any difficulties, please message us on our Discord, Forum, Twitter, or Facebook. We will respond to your inquiry as quickly as possible!