Created
September 29, 2020 00:34
-
-
Save carmandomx/3d73de81d5eede261908ce9fdfb9bdf6 to your computer and use it in GitHub Desktop.
ProtectedRoute (react-typescript)
This file contains 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 * 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