NA +91-8727899942 thecoderjob@gmail.com

CHAPTER - 48

Protected Route

It redirect the user to another link when the user not authourize for that particular link. 

Here's is the Code !!

// App.js

import React from "react";
import { BrowserRouter as Router, Switch } from "react-router-dom";
import PrivateRoute from "./PrivateRoute";
import Home from "./Home";
import Dashboard from "./Dashboard";
import Login from "./Login";

const App = () => {
  const isAuthenticated = true; // Determine if the user is authenticated
  return (
    <Router>
      <Switch>
        <Route path="/login" component={Login} />
        <PrivateRoute
          path="/dashboard"
          component={Dashboard}
          isAuthenticated={isAuthenticated}
        />
        <PrivateRoute
          path="/home"
          component={Home}
          isAuthenticated={isAuthenticated}
        />
        <Redirect from="/" to="/home" />
      </Switch>
    </Router>
  );
};

export default App;

// PrivateRoute.js

import React from "react";
import { Route, Redirect } from "react-router-dom";

const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => {
  return (
    <Route
      {...rest}
      render={(props) =>
        isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
      }
    />
  );
};

export default PrivateRoute;

Chapter 47

useLocation Hooks

Previous chapter

Chapter 49

fetch API | GET method

Next chapter

Get In Touch

NA

thecoderjob@gmail.com

+91-8727899942

Popular Links

© www.thecoderjob.com. All Rights Reserved.               Designed by HTML Codex