In Next.js, the useRouter
hook is part of the next/router
package, and it allows you to access the router object and its properties in functional components. This can be useful for programmatically navigating between pages or accessing information about the current route.
Here's how you can use the useRouter
hook in a Next.js component:
Import the hook:
Import the useRouter
hook from the next/router
package at the beginning of your component file.
javascriptimport { useRouter } from 'next/router';
Use the useRouter
hook:
Call the useRouter
hook within your functional component. This will give you access to the router object.
javascriptfunction MyComponent() {
const router = useRouter();
// Access router properties and methods
const { pathname, query, asPath, push } = router;
// Your component logic here
return (
<div>
{/* Your component JSX */}
</div>
);
}
The router
object provides various properties and methods, such as:
pathname
: A string representing the path of the current URL.query
: An object representing the query parameters of the current URL.asPath
: A string representing the actual path (including the query) shown in the browser.push
: A method to navigate to a new page.Example usage:
Here's a simple example that uses the push
method to navigate to a different page when a button is clicked:
javascriptimport { useRouter } from 'next/router';
function MyComponent() {
const router = useRouter();
const handleClick = () => {
// Navigate to the '/another-page' route
router.push('/another-page');
};
return (
<div>
<p>Current path: {router.pathname}</p>
<button onClick={handleClick}>Go to Another Page</button>
</div>
);
}
export default MyComponent;
In this example, clicking the button will trigger a navigation to the /another-page
route using the push
method from the router
object.
Remember to install the required dependencies if you haven't already by running:
bashnpm install next
Now you can use the useRouter
hook to interact with the router in your Next.js components.