Conditional Redirects in React Router
In React Router, you can redirect the user to a different route based on
a condition. The <Navigate> component is used for this.
Example: Redirect on a Specific Day
import { Navigate, useLocation } from "react-router-dom";
export default function Contact() {
const location = useLocation();
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const today = new Date();
const dayName = days[today.getDay()];
if (dayName === "Thursday") {
// Redirect to /login if it's Thursday
return <Navigate to="/login" replace state={{ from: location }} />;
}
return (
<>
<h1>Today is {dayName}</h1>
</>
);
}
Explanation
-
if (dayName === "Thursday")checks the condition. If true, React Router immediately redirects. -
state={{ from: location }}stores the page the user came from so you can send them back after login. -
replaceensures the redirect replaces the current entry in browser history (so the back button doesn’t cause a loop).
Typical Use Cases
- Redirect unauthenticated users to
/login. - Redirect users away from certain pages based on roles or permissions.
- Redirect based on feature flags, settings, or conditions like dates.

















