In the previous post we talked about how to create dynamic pages, and now let’s talk about extracting dynamic route data of each page.
Creating a dynamic website that displays different content depending on user input requires the ability to extract data from the URL. NextJS provides a powerful tool called useRouter, which is a custom hook created by the NextJS development team. In this post, we’ll explore how to use the useRouter hook to extract the exact element entered in the URL when a user clicks on a news item to view its details.
Extracting dynamic route data using useRouter() hook
To use the useRouter hook, we must first import it into our component. Once we have access to the useRouter hook, we can then use it to access the router object, which contains data and methods that can be used to extract the values encoded in the URL. The query property of the useRouter object allows us to access the URL segments by name, which we can then use to fetch the relevant data from a database.
//our-domain.com/news/news-details-id import { useRouter } from "next/router" export default function DetailsPage() { const router = useRouter(); const dynamicId = router.query.id console.log("ID:", dynamicId) return ( <h1>Details Page</h1> ) };
For example, if the URL is domain.com/news/news1, we can extract the value “news1” by calling console.log(router.query.id). This value can then be used to fetch the relevant news article data from a database and display it on the page.
By utilizing the useRouter hook and the query property, we can easily create dynamic and personalized web pages that respond to user input. The ability to extract data from the URL is especially useful when working with databases and APIs, as it allows us to fetch the correct data linked to the ID provided in the URL.
In conclusion, NextJS’s useRouter hook provides a powerful tool for creating dynamic web pages that respond to user input. By utilizing this hook and the query property, we can easily extract the values encoded in the URL and use them to fetch relevant data from databases and APIs. With NextJS, creating dynamic and personalized web pages has never been easier.
If you want to learn about how to do linking between pages in NextJS refer to this tutorial.
0 Comments