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

  1. Define — one clear sentence (the short answer above).
  2. Example — relate it to a project like ShopNest or your real work.
  3. Trade-off — when you would not use it.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details