Skip to content

Instantly share code, notes, and snippets.

@abhagsain
Created March 12, 2020 09:06
Show Gist options
  • Select an option

  • Save abhagsain/0d3ab4e53bf245fab8e21864314e6b95 to your computer and use it in GitHub Desktop.

Select an option

Save abhagsain/0d3ab4e53bf245fab8e21864314e6b95 to your computer and use it in GitHub Desktop.
Protected Route Using React Router Dom
const PrivateRoute = ({ component: Component, ...args }) => {
// user is the authenticated user pulled from the React Context
const { user } = useContext(AuthContext);
return (
<Route
{...args}
render={props => {
return user ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: {
from: props.location,
},
}}
/>
);
}}
/>
);
};
function Login(props) {
const { user } = useContext(AuthContext);
const { from } = props.location.state || { from: { pathname: "/" } };
if (user) {
return <Redirect to={from} />;
}
return (
<React.Fragment>
<Form
props={props}
authMessage={props.location.state && "You need to login first"}
/>
</React.Fragment>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment