Created
May 19, 2022 19:04
-
-
Save sourabhbagrecha/d0b2e6bd88da3572603eae4df480d3c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useContext } from "react"; | |
import { Navigate, Outlet, useLocation } from "react-router-dom"; | |
import { UserContext } from "../contexts/user.context"; | |
const PrivateRoute = (props) => { | |
// Fetching the user from the user context. | |
const { user } = useContext(UserContext); | |
const location = useLocation(); | |
// If the user is not logged in we are redirecting them | |
// to the login page. Otherwise we are letting them to | |
// continue to the page as per the URL using <Outlet />. | |
return user ? <Outlet /> : <Navigate to={`/login?redirectTo=${encodeURI(location.pathname)}`} />; | |
} | |
export default PrivateRoute; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment