Created
August 30, 2022 00:12
-
-
Save rushil1999/f660a850bc12aff55953367d81be742d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 React, {useContext} from 'react' | |
import {AuthContext} from '../contexts/AuthContextProvider'; | |
import { Navigate, useLocation } from 'react-router-dom'; | |
const PrivatePath = ({children}) => { | |
//Used to store the current location, so that it can be redirected back to this component after login | |
const location = useLocation() | |
//Reads the context value | |
const authContext = useContext(AuthContext); | |
const [authState] = authContext; | |
return( | |
<> | |
{/*If the authState is true, i.e. if user is logged in, render the `children` component from `props` else, navigate to Login component */} | |
{authState ? (<>{children}</>) : ( | |
<Navigate to="/login" state={{ from: location }} replace /> | |
) } | |
</> | |
) | |
} | |
export default PrivatePath; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment