How do you implement protected routes? Protected routes are used to restrict access to certain routes based on some condition (e.g., user authentication). You can create a wrapper component that checks the condition
nd either redirects or renders the requested route.
Example:
import { Redirect, Route } from 'react-router-dom';
function ProtectedRoute({ component: Component, ...rest }) {
const isAuthenticated = false; // Replace with your auth logic
return (
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/login" />
}
/>
);
}
function App() {
return (
<Router>
<Switch>
<Route path="/login" component={Login} />
<ProtectedRoute path="/dashboard" component={Dashboard} />
</Switch>
</Router>
);
}
In this example, if the user is not authenticated, they will be redirected to the login page
when trying to access the /dashboard route.