1Private Route--------
2
3import { Navigate,useLocation} from "react-router-dom"
4function Protecte({auth, children }) {
5 return auth ? children : <Navigate to="/login" />;
6
7}
8export default Protecte
9-----------------------------------
10
11App.js---
12<Route path="/admin" element={
13 <Protecte auth={isLoggedIn}>
14 <Admin />
15 </Protecte>
16 }
17 />
1import React from "react";
2import { Redirect, Route } from "react-router-dom";
3
4function ProtectedRoute({ component: Component, ...restOfProps }) {
5 const isAuthenticated = localStorage.getItem("isAuthenticated");
6 console.log("this", isAuthenticated);
7
8 return (
9 <Route
10 {...restOfProps}
11 render={(props) =>
12 isAuthenticated ? <Component {...props} /> : <Redirect to="/signin" />
13 }
14 />
15 );
16}
17
18export default ProtectedRoute;
19
20
1//create a file for example privateRoute.js
2import React, { Component } from "react";
3import { Route, Redirect } from "react-router-dom";
4import { isAuthenticated } from "./index";
5
6const PrivateRoute = ({ component: Component, ...rest }) => (
7 <Route
8 {...rest}
9 render={(props) =>
10 isAuthenticated() ? (
11 <Component {...props} />
12 ) : (
13 <Redirect
14 to={{ pathname: "/signin", state: { from: props.location } }}
15 />
16 )
17 }
18 />
19);
20
21export default PrivateRoute;
22
23
24
25//now import it to your routes file and use it
26
27import React from "react";
28import { BrowserRouter, Switch, Route } from "react-router-dom";
29import PrivateRoute from "./auth/privateRoute"
30
31import SignUp from "./user/signUp";
32import SignIn from "./user/signIn";
33import Home from "./core/home";
34import Dashboard from "./user/userDashboard";
35
36const Routes = () => {
37 return (
38 <BrowserRouter>
39 <Switch>
40 <Route path="/" exact component={Home} />
41 <Route path="/signin" exact component={SignIn} />
42 <Route path="/signup" exact component={SignUp} />
43 <PrivateRoute path="/dashboard" exact component={Dashboard} />
44 </Switch>
45 </BrowserRouter>
46 );
47};
48export default Routes;
49