Using Navigate for Redirects
You'll learn how to use React Router's <Navigate> component to automatically redirect users away from routes they shouldn't access.
The Core Idea
When protecting routes, you need a way to send unauthorized users elsewhere—typically to a login page. The <Navigate> component provides a declarative way to perform redirects. Instead of imperatively calling useNavigate(), you simply render <Navigate to="/login" /> and React Router handles the rest immediately.
Think of <Navigate> like a forwarding address: when React tries to render it, it automatically sends the browser to a different location instead of showing content.
How It Works in Protected Routes
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ children }) {
const isAuthenticated = checkAuth(); // Your auth logic
if (!isAuthenticated) {
return <Navigate to="/login" />;
}
return children;
}
When isAuthenticated is false, the component renders <Navigate> instead of the protected content. React Router immediately redirects the user to /login.
Replace vs Push
By default, <Navigate> replaces the current history entry (like navigate('/login', { replace: true })). This prevents users from hitting "back" and returning to the protected page they couldn't access:
<Navigate to="/login" replace />
Preserving the Intended Destination
You can pass the current location as state, allowing the login page to redirect users back after authentication:
import { Navigate, useLocation } from 'react-router-dom';
function ProtectedRoute({ children }) {
const location = useLocation();
const isAuthenticated = checkAuth();
if (!isAuthenticated) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
return children;
}
Key Takeaway: <Navigate> provides a clean, declarative way to redirect users from protected routes, automatically handling the navigation when rendered and optionally preserving context about where they came from.