Skip to content

Instantly share code, notes, and snippets.

@darmawan01
Created January 14, 2022 22:33
Show Gist options
  • Save darmawan01/25f56a96dca722245449650fdbd8a637 to your computer and use it in GitHub Desktop.
Save darmawan01/25f56a96dca722245449650fdbd8a637 to your computer and use it in GitHub Desktop.
Typescript Private Route React Router
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