Skip to content

Instantly share code, notes, and snippets.

@jmaicaaan
Last active May 30, 2021 02:17
Show Gist options
  • Save jmaicaaan/a39c18acc854e49b1e622759a8fe4e71 to your computer and use it in GitHub Desktop.
Save jmaicaaan/a39c18acc854e49b1e622759a8fe4e71 to your computer and use it in GitHub Desktop.
Protected Route
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