Introduction to Routing in Next.js
Routing is a crucial aspect of web applications that determines how URLs map to different parts of your application. In Next.js, routing is simple and follows a file-based approach. Each file you create in the "pages" directory becomes a route in your Next.js application.
Default Route
By default, Next.js uses the "index.js" file in the "pages" directory to represent the root route, which is accessible at /
. For example, if you create a file named "about.js" in the "pages" directory, it will be accessible at /about
.
Dynamic Routing
Next.js supports dynamic routing, which allows you to create routes with variable segments. You can use brackets [ ]
to indicate dynamic segments in your route files. For example:
<pre>
// pages/post/[id].js
import { useRouter } from 'next/router';
function PostPage() {
const router = useRouter();
const { id } = router.query;
return (
<div>
<h1>Post {id}</h1>
<p>This is a dynamic route for post {id}.</p>
</div>
);
}
export default PostPage;
</pre>
In this example, the route is dynamic, and the value of id
can be different for each URL segment.
Linking Between Pages
To navigate between pages in Next.js, you can use the Link
component. For example:
<pre>
import Link from 'next/link';
<Link href="/about">
<a>About Us</a>
</Link>
</pre>
This code creates a link to the "About Us" page. When users click the link, Next.js handles the client-side navigation without a full page reload.