Skip to content

Instantly share code, notes, and snippets.

@rushil1999
Created August 30, 2022 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rushil1999/f660a850bc12aff55953367d81be742d to your computer and use it in GitHub Desktop.
Save rushil1999/f660a850bc12aff55953367d81be742d to your computer and use it in GitHub Desktop.
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