In Next.js, the pages
directory is crucial as it determines your application's routes. The way you organize this directory defines your website's URL structure.
Pages Directory Structure:
In a Next.js project, the pages
directory contains React components, each representing a different page of your application. The filename of each component corresponds to the route path that it handles. Here's a basic example:
pages/
│
├── index.js # This component represents the homepage (route: /)
├── about.js # This component represents the about page (route: /about)
└── contact.js # This component represents the contact page (route: /contact)
Routing in Next.js:
Next.js uses a file-based routing system, meaning that the structure of the pages
directory determines the routing configuration of your application. When a user navigates to a specific URL, Next.js matches that URL to the corresponding file in the pages
directory and renders the associated React component.
For example:
Navigating to
/
will render theindex.js
component.Navigating to
/about
will render theabout.js
component.Navigating to
/contact
will render thecontact.js
component.
You can also create nested routes by organizing your files into subdirectories within the pages
directory. For example:
pages/
│
├── index.js # Homepage (route: /)
├── about.js # About page (route: /about)
├── contact.js # Contact page (route: /contact)
└── products/
├── index.js # Products listing page (route: /products)
└── [id].js # Dynamic product page (route: /products/:id)
In the above structure, navigating to /products
will render the products/index.js
component, and navigating to /products/123
will render the products/[id].js
component, where 123
is the dynamic parameter representing the product ID.
Dynamic Routes:
Next.js supports dynamic routes, allowing you to create pages with dynamic parameters in the URL. These dynamic parameters are enclosed in square brackets ([...]
) in the filename. For example, [id].js
represents a dynamic route with an id
parameter.
// pages/products/[id].js
function ProductPage({ id }) {
return <div>Product ID: {id}</div>;
}
export async function getServerSideProps({ params }) {
const { id } = params;
return {
props: {
id
}
};
}
export default ProductPage;
In the above example, the ProductPage
component receives the id
parameter from the URL, and you can fetch data associated with that ID using getServerSideProps
or getStaticProps
functions.
This is a simple overview of how pages and routing work in Next.js. Using files for routing makes it easy to organize your app's routes and create dynamic pages without much trouble.