How would you programmatically navigate a user to a different page after they complete an action, such as submitting a form?
Short answer
React Router provides a useNavigate hook that gives you a function to change the current page directly from your code, instead of relying on the user clicking a link, which is useful right after a successful form submission or login.
Advertisement
AModel answer
React Router provides a useNavigate hook that gives you a function to change the current page directly from your code, instead of relying on the user clicking a link, which is useful right after a successful form submission or login.
import { useNavigate } from 'react-router-dom';
function LoginForm() {
const navigate = useNavigate();
function handleLogin() {
loginUser().then(() => navigate('/dashboard'));
}
return <button onClick={handleLogin}>Log In</button>;
}Real-world example
A checkout page automatically redirects a customer to an order confirmation page the moment their payment is successfully processed, using useNavigate instead of requiring the customer to click a link themselves.
Likely follow-ups
- How would you navigate back to the previous page a user was on?
- What is the difference between using useNavigate and simply changing the browser's address directly?
Related topics