Skip to content

Instantly share code, notes, and snippets.

@mtreacy002
Created July 13, 2020 10:52
Show Gist options
  • Save mtreacy002/037e91889a5787c95e05c21dc689cae4 to your computer and use it in GitHub Desktop.
Save mtreacy002/037e91889a5787c95e05c21dc689cae4 to your computer and use it in GitHub Desktop.
Protected page with Reactjs
import React, { useContext } from "react";
import { Route, Redirect } from "react-router-dom";
import { AuthContext } from "./AuthContext";
export default function ProtectedRoute({ children, ...rest }) {
const { isAuth } = useContext(AuthContext);
return (
<Route
{...rest}
render={({ location }) => {
return isAuth ? (
children
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location }
}}
/>
);
}}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment