react router privateroute reactjs code example

Example 1: 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 2: react-router-config private routes

// Login.js

import React from 'react'

class Login extends React.Component {
   render() {
      const { from } = this.props.location.state || { from: {pathname: '/' } }
         return (
	    <div>
	       <p>You must log in to view this page at {from.pathname} </p>
	          <button onClick={this.login}>Log in </button>
	     </div>
	 )
   }
}

export default Login