react protected routes typescript

Solutions on MaxInterview for react protected routes typescript by the best coders in the world

showing results for - "react protected routes typescript"
Emma
04 Nov 2018
1/*SM*/
2/*example implemented with and FC and Typescript*/
3import { Redirect, Route, RouteProps } from 'react-router';
4
5export type ProtectedRouteProps = {
6  isAuthenticated: boolean;
7  authenticationPath: string;
8} & RouteProps;
9
10export default function ProtectedRoute({isAuthenticated, authenticationPath, ...routeProps}: ProtectedRouteProps) {
11  if(isAuthenticated) {
12    return <Route {...routeProps} />;
13  } else {
14    return <Redirect to={{ pathname: authenticationPath }} />;
15  }
16};
Michele
12 Apr 2017
1import * as React from 'react';
2import {
3    Route, 
4    Redirect,
5    RouteProps,
6    RouteComponentProps
7} from "react-router-dom";
8
9interface PrivateRouteProps extends RouteProps {
10    isAuthenticated: boolean;
11  // Would reccommend this comes from a global state manager
12  // such as redux, shown using basic props here
13}
14
15export class PrivateRoute extends Route<PrivateRouteProps> {
16    render() {
17        return (
18            <Route render={(props: RouteComponentProps) => {
19                if(!this.props.isAuthenticated) {
20                    return <Redirect to='/login' />
21                } 
22
23                if(this.props.component) {
24                    return React.createElement(this.props.component);
25                } 
26
27                if(this.props.render) {
28                    return this.props.render(props);
29                }
30            }} />
31        );
32    }
33}
34
35// How To Use Them :::::
36<PrivateRoute 
37    path='/dashboard'
38    component={DashboardPage} 
39    isAuthenticated={props.isAuthenticated}
40/>
41      // OR
42<PrivateRoute 
43    path='/checkout'
44    isAuthenticated={props.isAuthenticated}
45    render={() => (
46       <CheckoutPage auth={props.auth} />
47    )} 
48/>