Skip to content

Instantly share code, notes, and snippets.

@garikaijenje
Last active April 10, 2021 19:55
Show Gist options
  • Save garikaijenje/58f4aebc7b0661222c7b5d37bc8241fb to your computer and use it in GitHub Desktop.
Save garikaijenje/58f4aebc7b0661222c7b5d37bc8241fb to your computer and use it in GitHub Desktop.
React Router Protected Route Component

A custom component that checks if user is loggedIn, otherwise it redirects to the login page

const ProtectedRoute = ({ component: Component, ...rest }) => {
  const authenticated = true; // change this to your isLoggedIn state
  return (
   <Route {...rest} render={(props) => (
      authenticated === true ?
         <Component {...props} /> : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />   
   )} />
  )
};
  1. Change the authenticated state to match your login state
  2. state: { from: props.location } is used to return the user back to the page they were redirected from

Example Usage

<ProtectedRoute exact path='/dashboard' component={Dashboard} />
<Route exact path='/login' component={Login} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment