Skip to main content

Introduction to Pages in Nextjs

Next.js is a popular framework for building React applications. One of its core features is its file-system based routing. In a nutshell, this means that the pages of your Next.js application are represented as files in the pages directory. This article will explore this key concept in detail.

What are Pages in Next.js?

In Next.js, a page is a React Component exported from a .js, .jsx, .ts, or .tsx file in the pages directory. Each page is associated with a route based on its file name. For instance, if you create a pages/about.js file, it will be accessible at www.yourwebsite.com/about.

Here's what a basic page in Next.js might look like:

export default function Home() {
return <div>Welcome to Next.js!</div>
}

Routing in Next.js

Next.js has a file-system based router built on the concept of pages. When a file is added to the pages directory, it's automatically available as a route.

For example, if you create pages/about.js, it will be accessible at www.yourwebsite.com/about. The route name is determined by the file name. The index.js file is mapped to the root route (/).

Nested Routes

You can create nested paths in Next.js by adding files and folders in the pages directory. For example, to create a route for www.yourwebsite.com/posts/first-post, you would create a file at pages/posts/first-post.js.

Dynamic Route Segments

Next.js supports dynamic routes, which are routes that change based on data. This is accomplished by creating a file with square brackets ([]) in the pages directory.

For example, to create a dynamic route for blog posts, you would create a file at pages/posts/[id].js. The [id] part is a placeholder that can be replaced with any value, like pages/posts/first-post.

Linking Between Pages

To navigate between pages, you can use the Link component from the next/link package. This component enables client-side navigation between pages in your application.

Here's how you can use it:

import Link from 'next/link'

export default function Home() {
return (
<div>
<h1>My Blog</h1>
<ul>
<li>
<Link href="/posts/first-post">
<a>First Post</a>
</Link>
</li>
</ul>
</div>
)
}

In this example, clicking on "First Post" will navigate to the /posts/first-post page.

Conclusion

Next.js offers a simple and powerful way to manage routing in your React applications. By leveraging the file-system based routing, you can create complex applications with dynamic and nested routes. The Link component makes navigation between pages a breeze. By understanding these concepts, you can start building impressive Next.js applications!