protected routes react typescript code example
Example 1: react protected routes typescript
import * as React from 'react';
import {
Route,
Redirect,
RouteProps,
RouteComponentProps
} from "react-router-dom";
interface PrivateRouteProps extends RouteProps {
isAuthenticated: boolean;
}
export class PrivateRoute extends Route<PrivateRouteProps> {
render() {
return (
<Route render={(props: RouteComponentProps) => {
if(!this.props.isAuthenticated) {
return <Redirect to='/login' />
}
if(this.props.component) {
return React.createElement(this.props.component);
}
if(this.props.render) {
return this.props.render(props);
}
}} />
);
}
}
<PrivateRoute
path='/dashboard'
component={DashboardPage}
isAuthenticated={props.isAuthenticated}
/>
<PrivateRoute
path='/checkout'
isAuthenticated={props.isAuthenticated}
render={() => (
<CheckoutPage auth={props.auth} />
)}
/>
Example 2: react router dom private route typescript
import React from "react";
import { Route, Redirect } from "react-router-dom";
const PrivateRoute: React.FC<{
component: React.FC;
path: string;
exact: boolean;
}> = (props) => {
const condition = performValidationHere();
return condition ? (<Route path={props.path} exact={props.exact} component={props.component} />) :
(<Redirect to="/page/login" />);
};
export default PrivateRoute;
Example 3: react router dom private route typescript
import * as React from "react";
import { Route } from "react-router-dom";
interface IProps {
exact?: boolean;
path: string;
component: React.ComponentType<any>;
}
const LoggedOutRoute = ({
component: Component,
...otherProps
}: IProps) => (
<>
<header>Logged Out Header</header>
<Route
render={otherProps => (
<>
<Component {...otherProps} />
</>
)}
/>
<footer>Logged Out Footer</footer>
</>
);
export default LoggedOutRoute;