Skip to content

Instantly share code, notes, and snippets.

@carmandomx
Created September 29, 2020 00:34
Show Gist options
  • Save carmandomx/3d73de81d5eede261908ce9fdfb9bdf6 to your computer and use it in GitHub Desktop.
Save carmandomx/3d73de81d5eede261908ce9fdfb9bdf6 to your computer and use it in GitHub Desktop.
ProtectedRoute (react-typescript)
import * as React from 'react';
import { Redirect, Route, RouteProps } from 'react-router';
export interface ProtectedRouteProps extends RouteProps {
isAuthenticated: boolean;
isAllowed: boolean;
restrictedPath: string;
authenticationPath: string;
}
export const ProtectedRoute: React.FC<ProtectedRouteProps> = props => {
let redirectPath = '';
if (!props.isAuthenticated) {
redirectPath = props.authenticationPath;
}
if (props.isAuthenticated && !props.isAllowed) {
redirectPath = props.restrictedPath;
}
if (redirectPath) {
const renderComponent = () => <Redirect to={{ pathname: redirectPath }} />;
return <Route {...props} component={renderComponent} render={undefined} />;
} else {
return <Route {...props} />;
}
};
export default ProtectedRoute;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment