Answers for "phow to make routes private"

0

how to make routes private

//create a file for example privateRoute.js
import React, { Component } from "react";
import { Route, Redirect } from "react-router-dom";
import { isAuthenticated } from "./index";

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      isAuthenticated() ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{ pathname: "/signin", state: { from: props.location } }}
        />
      )
    }
  />
);

export default PrivateRoute;



//now import it to your routes file and use it

import React from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import PrivateRoute from "./auth/privateRoute"

import SignUp from "./user/signUp";
import SignIn from "./user/signIn";
import Home from "./core/home";
import Dashboard from "./user/userDashboard";

const Routes = () => {
  return (
    <BrowserRouter>
    <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/signin" exact component={SignIn} />
        <Route path="/signup" exact component={SignUp} />
        <PrivateRoute path="/dashboard" exact component={Dashboard} />
      </Switch>
    </BrowserRouter>
  );
};
export default Routes;
Posted by: Guest on October-25-2021

Code answers related to "phow to make routes private"

Code answers related to "Javascript"

Browse Popular Code Answers by Language