Created
January 14, 2022 22:33
-
-
Save darmawan01/25f56a96dca722245449650fdbd8a637 to your computer and use it in GitHub Desktop.
Typescript Private Route React Router
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 React from 'react'; | |
import { | |
Navigate, Route, RouteProps | |
} from 'react-router-dom'; | |
interface PrivateRouteProps extends RouteProps { | |
// tslint:disable-next-line:no-any | |
component: any; | |
isAuthenticated: boolean; | |
} | |
const PrivateRoute = (props: PrivateRouteProps) => { | |
const { component: Component, isAuthenticated, ...rest } = props; | |
return ( | |
<Route | |
{...rest} | |
children={(routeProps: any) => | |
isAuthenticated ? ( | |
<Component {...routeProps} /> | |
) : ( | |
<Navigate | |
to={{ pathname: '/signin' }} | |
state={{ from: routeProps.location }} | |
/> | |
) | |
} | |
/> | |
); | |
}; | |
export default PrivateRoute; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment