How can you implement a private route that requires authentication before rendering a component in React Router

0 votes
With the help of code may i know How can you implement a private route that requires authentication before rendering a component in React Router?
4 days ago in Node-js by Nidhi
• 15,820 points
34 views

1 answer to this question.

0 votes

Basic Private Route Implementation (v6)

import { Navigate, Outlet } from 'react-router-dom';

const PrivateRoute = ({ isAuthenticated }) => {

  return isAuthenticated ? <Outlet /> : <Navigate to="/login" replace />;

};

Usage in Route Configuration

import { Routes, Route } from 'react-router-dom';

function App() {

  const [isAuthenticated] = useAuth(); // Your auth state

  return (

    <Routes>

      {/* Public routes */}

      <Route path="/login" element={<LoginPage />} />

      {/* Protected routes */}

      <Route element={<PrivateRoute isAuthenticated={isAuthenticated} />}>

        <Route path="/dashboard" element={<Dashboard />} />

        <Route path="/profile" element={<Profile />} />

      </Route>

      {/* Catch-all */}

      <Route path="*" element={<NotFound />} />

    </Routes>

  );

}

answered 4 days ago by anonymous

Related Questions In Node-js

0 votes
1 answer

How can you implement nested routes in a React application using React Router?

To implement nested routes in a React ...READ MORE

answered 4 days ago in Node-js by anonymous
33 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How do you model a many-to-many relationship in MongoDB with an example?

In MongoDB, a many-to-many relationship can be ...READ MORE

answered Feb 23 in Node-js by Kavya
127 views
0 votes
1 answer

What is the difference between RDBMS relationships and MongoDB’s data model?

Feature RDBMS (SQL Databases) MongoDB (NoSQL Document Database) Data Structure Tables ...READ MORE

answered Feb 23 in Node-js by Kavya
79 views
0 votes
1 answer
0 votes
1 answer

Write a query for a compound index to optimize a search operation in MongoDB.

A compound index improves search performance by ...READ MORE

answered Feb 23 in Node-js by Kavya
109 views
0 votes
1 answer
0 votes
1 answer

How can you programmatically navigate to a different route in React Router v5?

In React Router v5, you can programmatically ...READ MORE

answered 4 days ago in Node-js by anonymous
26 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP