Next.js is a powerful framework that simplifies the process of building web applications. If you’ve worked with React.js, you’re probably familiar with the concept of routing. However, when it comes to Next.js, routing is even simpler. All you need to do is create a folder or file, and that’s it. Unlike React, where you have to install a separate library for routing, Next.js provides an easy and straightforward approach. Let’s dive into it.
Table of contents
Open Table of contents
Static Routing
Static routing in Next.js 13 is as simple as creating a new file in the ‘pages’ directory. The path to the file becomes the URL path, and the exported React component in the file becomes the page’s content. For example if you want about page. all you have to do is to create folder called about inside folder you name your file page.js, it will be accessible at /about.
For example:
pages/
├─ about
├─── page.js
this will automatically generate the following routes in your Next.js application: ‘/about’ (from ‘page.js’).
Route Grouping
In Next.js, you can group routes by creating subfolders within the ‘pages’ directory. However, there are some nuances to be aware of:
- If you create a file named ‘page.js’ within a subfolder (let’s call it ‘Map’), this will not affect the route for ‘Map’. The ‘Map’ route will continue to work as expected.
- However, if there’s an exact match between a grouped route and another route, it can cause a collision. This could result in an error or a 404 Not Found page.
- To manage your grouped routes effectively, you might want to create a layout for them. This allows you to group them together under one folder (like ‘Map’).
Dynamic Routing
In static route we know the route we want to go but what if we don’t the name of route. it could come from the database or blog post slug. it’s dynamic data so we need to use dynamic route to access.
Dynamic routing allows you to create routes that correspond to patterns, rather than fixed paths. In Next.js 13, you define dynamic routes by naming a page with square brackets. For example, ‘pages/post/[id].js’ matches ‘/post/1’, ‘/post/abc’, and so on.
Here’s an example of how you might use dynamic routing:
// pages/post/[id].js
import { useRouter } from 'next/router'
export default function Post() {
const router = useRouter()
const { id } = router.query
return <p>Post: {id}</p>
}
In this example, the page will display the text “Post: ” followed by the value of id.
Conclusion
In conclusion, whether you choose static or dynamic routing in Next.js depends on your specific needs and the structure of your application. Both methods provide an easy and efficient way to manage routes in your Next.js application.
Thanks for Reading 🙏🏻