Answers for "how to protected a route in react router with typescript"

1

how to protected a route in react router with typescript

/*SM*/
/*example implemented with and FC and Typescript*/
import { Redirect, Route, RouteProps } from 'react-router';

export type ProtectedRouteProps = {
  isAuthenticated: boolean;
  authenticationPath: string;
} & RouteProps;

export default function ProtectedRoute({isAuthenticated, authenticationPath, ...routeProps}: ProtectedRouteProps) {
  if(isAuthenticated) {
    return <Route {...routeProps} />;
  } else {
    return <Redirect to={{ pathname: authenticationPath }} />;
  }
};
Posted by: Guest on July-07-2021
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;
  // 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} />
    )} 
/>
Posted by: Guest on January-28-2020

Code answers related to "how to protected a route in react router with typescript"

Code answers related to "TypeScript"

Browse Popular Code Answers by Language