How do you create protected routes in React

0 votes
With the help of proper programming can you tell me How do you create protected routes in React?
Feb 22 in Node-js by Nidhi
• 11,580 points
77 views

1 answer to this question.

0 votes

Creating Protected Routes in React (React Router v6)

1. Create a ProtectedRoute Component

import { Navigate } from "react-router-dom";

const ProtectedRoute = ({ children }) => {

  const isAuthenticated = localStorage.getItem("authToken"); // Example auth check

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

};

export default ProtectedRoute;

2. Use ProtectedRoute in App.js

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

import Home from "./Home";

import Dashboard from "./Dashboard";

import Login from "./Login";

import ProtectedRoute from "./ProtectedRoute";

const App = () => {

  return (

    <Router>

      <Routes>

        <Route path="/" element={<Home />} />

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

        <Route 

          path="/dashboard" 

          element={

            <ProtectedRoute>

              <Dashboard />

            </ProtectedRoute>

          } 

        />

      </Routes>

    </Router>

  );

};

export default App;

answered Feb 23 by Kavya

Related Questions In Node-js

0 votes
1 answer

How do I create a custom object in react?

Creating a custom popover in React enhances ...READ MORE

answered Dec 31, 2024 in Node-js by Navya
97 views
0 votes
1 answer
0 votes
1 answer

How do you implement routing in a React application?

Implementing Routing in a React Application (React ...READ MORE

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

How do you handle nested dynamic routes with React-Router?

Handling Nested Dynamic Routes in React Router ...READ MORE

answered Feb 24 in Node-js by Kavya
76 views
0 votes
1 answer

How to pass parameters with react-router?

Passing Parameters with React Router 1. Define a ...READ MORE

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

What is the use of Switch in React Router?

In React Router v5, <Switch> is used ...READ MORE

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

What is the difference between BrowserRouter and createBrowserRouter?

Feature BrowserRouter (React Router v5 & v6) createBrowserRouter (React ...READ MORE

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

How do I create a custom popover in React?

Create a custom popover in React by ...READ MORE

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

How do I create a custom slider in React?

Create a custom slider in React by ...READ MORE

answered Feb 23 in Node-js by Kavya
107 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