Search
 
SCRIPT & CODE EXAMPLE
 

TYPESCRIPT

react protected routes typescript

import * as React from 'react';
import {
    Route, 
    Redirect,
    RouteProps,
    RouteComponentProps
} from "react-router-dom";

interface PrivateRouteProps extends RouteProps {
    isAuthenticated: boolean;
  // Would reccommend this comes from a global state manager
  // such as redux, shown using basic props here
}

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);
                }
            }} />
        );
    }
}

// How To Use Them :::::
<PrivateRoute 
    path='/dashboard'
    component={DashboardPage} 
    isAuthenticated={props.isAuthenticated}
/>
      // OR
<PrivateRoute 
    path='/checkout'
    isAuthenticated={props.isAuthenticated}
    render={() => (
       <CheckoutPage auth={props.auth} />
    )} 
/>
Comment

PREVIOUS NEXT
Code Example
Typescript :: regex match round brackets contains any characters 
Typescript :: capacitor base64 to file 
Typescript :: echarts is not defined 
Typescript :: Please make sure you have the correct access rights and the repository exists. 
Typescript :: increment all elements list python 
Typescript :: loop through string typescript 
Typescript :: exists query elasticsearch 5.4 
Typescript :: add 1 to all elements in array python 
Typescript :: ng-select disabled 
Typescript :: key value typescript 
Typescript :: angular output send click event to parent 
Typescript :: regex remove brackets and contents 
Typescript :: apexcharts colors function 
Typescript :: angular subscribe catch stat 
Typescript :: eslint airbnb react typescript 
Typescript :: typescript extend interface 
Typescript :: sort a list of ints python in descending order 
Typescript :: classes in typescript 
Typescript :: typeorm query builder update relations filed 
Typescript :: 10 digit mobile number validation pattern in javascript 
Typescript :: how to append to a list of lists in python 
Typescript :: google fonts icons size classes 
Typescript :: Cannot show Automatic Strong Passwords for app bundleID: com.williamyeung.gameofchats due to error: iCloud Keychain is disabled 
Typescript :: c# linq get list of objects based on another list 
Typescript :: live airplane tracker 
Typescript :: making barplots in r 
Typescript :: promise allsettled typescript 
Typescript :: fgets input from user 
Typescript :: basic variable types in typescript 
Typescript :: typescript pass a function as an argunetn 
ADD CONTENT
Topic
Content
Source link
Name
1+3 =