How to use the useRouter hook for dynamic navigation in Next.js



Image not found!!

In Next.js, the useRouter hook is a utility provided by the next/router module that allows you to access the router object. You can use this hook for dynamic navigation by obtaining information about the current route and manipulating it to create dynamic links or perform navigation based on certain conditions.

Here's a basic example of how to use the useRouter hook for dynamic navigation in Next.js:

  1. Import the useRouter hook at the top of your component file:
javascript
import { useRouter } from 'next/router';
  1. Use the useRouter hook within your functional component:
javascript
import { useRouter } from 'next/router'; function MyComponent() { const router = useRouter(); // Access the current route parameters const { query, pathname } = router; // Example of dynamic navigation based on route parameters const handleDynamicNavigation = () => { // Replace 'dynamic-page' with the actual page route router.push('/dynamic-page/[id]', `/dynamic-page/${query.id}`); }; return ( <div> <p>Current Path: {pathname}</p> <p>Query Parameters: {JSON.stringify(query)}</p> {/* Example of dynamic navigation */} <button onClick={handleDynamicNavigation}>Go to Dynamic Page</button> </div> ); } export default MyComponent;

In this example:

  • The useRouter hook is used to obtain the router object, which contains information about the current route.
  • The pathname property represents the path of the current route.
  • The query property represents the query parameters of the current route.
  • The handleDynamicNavigation function demonstrates how to perform dynamic navigation by using the router.push method. In this case, it pushes the user to a dynamic page based on the id query parameter.

Remember to replace the page route ('/dynamic-page/[id]') and any other placeholders with your actual routes and parameters.

By using the useRouter hook, you can access and manipulate route information easily, making it suitable for dynamic navigation scenarios in your Next.js application.