In React Router v6, we can use the useNavigate hook to navigate programmatically.
1. Using useNavigate Hook (React Router v6+)
Example:
import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
const handleNavigate = () => {
navigate('/about'); // Navigate to '/about'
};
return (
<div>
<button onClick={handleNavigate}>About</button>
</div>
);
}
navigate('/about'): This will navigate to the /about route.
The navigate function can also accept additional options, like replace or state.
Example with options:
import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
const handleNavigate = () => {
navigate('/about', { replace: true, state: { from: 'home' } });
};
return (
<div>
<button onClick={handleNavigate}>Go to About</button>
</div>
);
}