Last active
May 30, 2021 02:17
-
-
Save jmaicaaan/a39c18acc854e49b1e622759a8fe4e71 to your computer and use it in GitHub Desktop.
Protected Route
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 { | |
Route, | |
RouteProps, | |
matchPath, | |
} from 'react-router-dom'; | |
import { GuardFunction } from '../types/guard'; | |
export type ProtectedRouteProps = RouteProps & { | |
guards: GuardFunction[]; | |
fallback: () => JSX.Element | null; | |
}; | |
export const ProtectedRoute = ({ | |
fallback, | |
guards, | |
...rest | |
}: ProtectedRouteProps) => { | |
const { | |
pathname, | |
} = window.location; | |
const matchResult = matchPath(pathname, rest); | |
const hasMatchedRoute = !!matchResult; | |
/** | |
* Make sure the user is accessing the path it intends to access | |
* before running any guard functions. | |
* Match the route first before validating (running the guards) | |
*/ | |
if (hasMatchedRoute) { | |
const guardArgs = rest; | |
const canBeRendered = guards.every(guard => guard(guardArgs)); | |
if (guards.length && !canBeRendered) { | |
return fallback(); | |
} | |
} | |
return ( | |
<Route | |
{...rest} | |
/> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment