Mid
From PDF
React
React.js
How do you implement protected routes?
Short answer: 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 and either redirects or renders the requested route.
Example code
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.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png