In the previous video, we learned about grouping routes in Next.js. Now, let's explore how we can intercept a route and render a different page by intercepting it. But first, let's understand what interception means.
Creating Folders
To demonstrate interception, let's start by creating two folders: "first page" and "second page". In the "first page" folder, we'll add a file called "page.tsx". Similarly, in the "second page" folder, we'll add a file called "page.tsx" as well.
Routing Setup
To navigate to these pages, let's add a couple of link buttons. One for the first page and another for the second page. Now, let's check if the routing is working correctly. On the main page, we should see the two links for the first and second pages.
Intercepting the Route
In order to intercept the route, we need to modify the routing setup. Let's make some changes. Inside the first page folder, add a file called "index.tsx". Similarly, inside the second page folder, add a file called "index.tsx" as well.
Now, when we click on the second page link, instead of navigating to the second page, we will try to navigate to a different page by intercepting the route.
The Intercepted Page
To intercept the second page, we need to add a dot ('.') in the first page file path. This indicates that the second page is within the first page folder structure. Now, let's see how this works.
When we click on the second page link, instead of seeing the content of the second page, we see the intercepted content. This is because of the interception we added in the routing setup. The intercepted page is displayed instead of the actual second page content.
However, it's important to note that the interception only happens the first time. If we refresh the page, the routing will work as expected and directly navigate to the second page.
Use Cases for Intercepting Pages
Intercepting pages can be useful in various scenarios. For example, if the second page makes an API call to fetch some data and there is a slight delay in loading the content, you can use the intercepted page to display a loading message. Once the content of the second page is ready, you can navigate to it and remove the intercepted page.
This allows you to provide a better user experience by giving them feedback about the loading process and preventing them from seeing a blank or partially loaded page.
Conclusion
Intercepting routes in Next.js allows you to modify the default behavior of navigating to a page. By intercepting the route, you can display a different page or perform some actions before navigating to the actual page.
Whether it's displaying a loading message, fetching data from an API, or performing any other action, intercepting pages can greatly enhance the user experience. Use it wisely and strategically to make your Next.js applications more powerful and user-friendly.
Thank you for reading! Stay tuned for the next video!
Comments
Post a Comment