privateroute react code example

Example 1: private route in react js

import React from 'react';
import {
  BrowserRouter,
  Route,
  Switch,
  Redirect
} from 'react-router-dom';
import decode from 'jwt-decode';

import Home from './Home';
import Register from './Register';
import Login from './Login';
import PrivateComponent1 from './PrivateComponent1';
import PrivateComponent2 from './PrivateComponent2';


const isAuthenticated = () => { 
  	  const token = localStorage.getItem('token');
  try {
    if(token){
      return true;
    }
    else{
      return false;
    }
  } catch (error) {
    return false;
  }
}

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

export default () => (
  <BrowserRouter>
    <Switch>
      <Route path="/" exact component={Home}/>
      <Route path="/register" exact component={Register}/>
      <Route path="/login" exact component={Login}/>
      <PrivateRoute path="/private1/:id?" exact component={PrivateComponent1}/>
      <PrivateRoute path="/private2" exact component={PrivateComponent2}/>
    </Switch>
  </BrowserRouter>
);

Example 2: private routes in react

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

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

Example 3: private route in react js

const PrivateRoute = ({component: Component, ...rest}) => {
  const {isAuthenticated} = rest;

  return (
    <Route {...rest} render={props => (
      isAuthenticated ? (
        <Component {...props}/>
      ) : (
        <Redirect to={{
          pathname: '/login',
          state: {from: props.location}
        }}/>
      )
    )}
    />
  );
};

PrivateRoute.propTypes = {
  isAuthenticated: PropTypes.bool.isRequired,
};

function mapStateToProps(state) {
  return {
    isAuthenticated: state.user.isAuthenticated,
  };
}

export default connect(mapStateToProps)(PrivateRoute);