Client-Side Navigation with useNavigate
Showcase client-side navigation in Next.js 14 using the `useNavigate` hook, illustrating programmatic navigation in response to user actions.
import { useNavigate } from 'react-router-dom';
function MyComponent() {
// Get the navigate function from the useNavigate hook
const navigate = useNavigate();
// Function to handle navigation on some event, like a button click
const goToHomePage = () => {
// Use the navigate function to programmatically change the route
navigate('/');
};
return (
<div>
<h1>MyComponent</h1>
<button onClick={goToHomePage}>Go to Home Page</button>
</div>
);
}
This piece of code imports the useNavigate hook from react-router-dom, defines a component called MyComponent, which uses the navigate function to change the route to the home page when the button is clicked.