In next.js, the file system enables routing in the application. It automatically treats every file with the extensions .js, .jsx, .ts, or .tsx under the pages directory as a route.
Working of the Next.js Routing
Next.js uses a file system based routing for creating a new route. Each Next.js project has a
pages folder. Every file and folder inside the pages folder is considered a route.
In the pages folder, the first root route is index.js which renders on the
/ path. Also, we can create nested routes by creating a folder inside the pages directory.
Let us consider the following example :
Here we have five pages.
- index.js maps to the path
- px.js maps to the path
- careers.js maps to the path
- reactBlog.js is in the sub folder, and we can access it on path
- We can access nextjsBlog.js on path
Types of Routing in Next.js
Next.js has three types of routes
- Index Route
- Nested Route
- Dynamic Route
In the pages directory, we have the index.js file, which is automatically routed to the root folder.
Here we created a file in the pages folder named index.js, it could be accessed using
/. Inside the pages directory, we have a blog folder containing an index.js file. It would be accessible on
Nested routes allow you to create a route inside the parent component. If we created nested folders in the pages directory, then routes will be nested.
we created a new folder blog with a routing-in-nextjs.js file in it, we can access this page by visiting
Next.js can accept URL parameters and create dynamic routes using the bracket syntax.
If we create a new page in the pages directory called [username].js then the component exported from this file, could access the parameter id and render content accordingly.
This can be accessed by going to
Accessing router in React components
To access the router object inside the react components, we have to use the useRouter() hook or withRouter.
The following example shows us how to access the router in react component.
The router object provides the following methods:
It handles the client-side transitions.
url is the route of the new state.
as is the url to be shown in a browser.
options is the optional object sent by the router.push().
options can be -
Scroll - controls the scrolling to the top page. By default, it is true.
Locale - denotes the locale of a new page.
router.replace() prevent adding new entry in history stack.
It navigates back to history. It behaves similar to the browser back button. It executes
It reloads the current page. It behaves similar to the browser's refresh button. It executes
It prefetch pages for faster client-side transitions. It is only helpful for navigations without next/link, as next/link takes care of prefetching pages automatically.
Note: This is only a production-only feature.
We have quickly gone over the next/router, and it's working. Then, we saw routing types and their examples. We learned how to inject router in react components and some router methods with examples.