Skip to content

Instantly share code, notes, and snippets.

@drex44
Created August 28, 2018 15:19
Show Gist options
  • Save drex44/56bb0fe08b836e30c20572b73e596619 to your computer and use it in GitHub Desktop.
Save drex44/56bb0fe08b836e30c20572b73e596619 to your computer and use it in GitHub Desktop.
Create private/protected route in react using react router v4
import { Switch, Route, Redirect } from "react-router-dom";
export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
props.isLoggedIn === true ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/",
state: { from: props.location }
}}
/>
)
}
/>
);
@drex44
Copy link
Author

drex44 commented Aug 28, 2018

How to use this component,

let isLoggedIn = false;

<PrivateRoute
  isLoggedIn={isLoggedIn}
  path="/editList/:id"
  component={EditList}
/>;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment