41

I was trying to create a <PrivateRoute> as describe in the react-router documents using TypeScript. Can anyone help me out?

The privateRoute in react-router document:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{pathname: '/login', state: { from: props.location }
   }}/>
  )
 )}/>
)

Below is my TypeScript version(it won't work) :

const PrivateRoute = (theProps: { path: string, component: React.SFC<RouteComponentProps<any> | undefined> | React.ComponentClass<RouteComponentProps<any> | undefined> }) => {
    return <Route path={theProps.path} render={props => (
        fakeAuth.isAuthenticated ? (
            <React.Component {...theProps} /> <!-- **** It will raise error *** -->
        ) : (
                <Redirect to={{
                    pathname: '/',
                    state: { from: props.location }
                }} />
            )
    )} />
}

The <React.Component {...thisProps} /> is not right. The error is: NodeInvocationException: inst.render is not a function TypeError: inst.render is not a function

Robin
  • 6,726
  • 4
  • 47
  • 75
Charlie
  • 1,520
  • 1
  • 12
  • 25

4 Answers4

87

Probably the error has to do with the typing and the implicit return in rendering. When you fix this you get ultimately to something like this:

const PrivateRoute = ({component, isAuthenticated, ...rest}: any) => {
    const routeComponent = (props: any) => (
        isAuthenticated
            ? React.createElement(component, props)
            : <Redirect to={{pathname: '/login'}}/>
    );
    return <Route {...rest} render={routeComponent}/>;
};

This component can be used like this:

<PrivateRoute
    path='/private'
    isAuthenticated={this.props.state.session.isAuthenticated}
    component={PrivateContainer}
/>

There are a few draw backs with the solution above. One of the is that you lose type safety.

Probably extending the Route component is the better idea.

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

export interface ProtectedRouteProps extends RouteProps {
    isAuthenticated: boolean;
    authenticationPath: string;
}

export class ProtectedRoute extends Route<ProtectedRouteProps> {
    public render() {
        let redirectPath: string = '';
        if (!this.props.isAuthenticated) {
            redirectPath = this.props.authenticationPath;
        }

        if (redirectPath) {
            const renderComponent = () => (<Redirect to={{pathname: redirectPath}}/>);
            return <Route {...this.props} component={renderComponent} render={undefined}/>;
        } else {
            return <Route {...this.props}/>;
        }
    }
}

So you can use the component like this:

const defaultProtectedRouteProps: ProtectedRouteProps = {
    isAuthenticated: this.props.state.session.isAuthenticated,
    authenticationPath: '/login',
};

<ProtectedRoute
    {...defaultProtectedRouteProps}
    exact={true}
    path='/'
    component={ProtectedContainer}
/>

Update (Nov 2019)

If you prefer to write functional components you can do it in a very similar manner. This also works with React Router 5:

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

export interface ProtectedRouteProps extends RouteProps {
  isAuthenticated: boolean;
  isAllowed: boolean;
  restrictedPath: string;
  authenticationPath: string;
}

export const ProtectedRoute: React.FC<ProtectedRouteProps> = props => {
  let redirectPath = '';
  if (!props.isAuthenticated) {
    redirectPath = props.authenticationPath;
  }
  if (props.isAuthenticated && !props.isAllowed) {
    redirectPath = props.restrictedPath;
  }

  if (redirectPath) {
    const renderComponent = () => <Redirect to={{ pathname: redirectPath }} />;
    return <Route {...props} component={renderComponent} render={undefined} />;
  } else {
    return <Route {...props} />;
  }
};

export default ProtectedRoute;

Update (Dec 2019)

If you want to redirect a user to the path the user wanted to access first, you need to remember the path, so you can redirect after successful authentication. The following answer will guide you through that:

Redirecting a user to the page they requested after successful authentication with react-router-dom

Update (Mar 2021)

The solution above is a bit outdated. The ProtectedRoute component can simply be written as follows:

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

If you use React Router V6 you need to replace Redirect with Navigate. A full example with redirection to the originally requested page can be found here:

Robin
  • 6,726
  • 4
  • 47
  • 75
  • what if I connect ProtectedRoute to redux to get the IsAuthenticated property ? would it cause performance issues ? – David Noreña Jan 12 '18 at 20:18
  • No, I don't think so. There is just one if/else more compared to the original use of `Route`. – Robin Jan 12 '18 at 22:29
  • 1
    Brilliant solution @Robin. :) I'll add my 2 cents here: 1. ProtectedRouteProps need not have isAuthenticated because it highly depends on this.props.state. Which means each component will have to have that info. Instead Devs can use some sort of GlobalState / GlobalStore or Mobx based observable variable to detect isAuthenticated(or is, props will not get passed to – Piyush May 29 '19 at 05:29
  • @Piyush: I disagree with your idea to omit the `isAuthenticated` from the props, because the component won't be reusable anymore. I suggest to create some kind of Router container component, where you set up all the routes and bind the state. – Robin Nov 09 '19 at 10:12
  • Makes sense. Thanks @Robin – Piyush Nov 10 '19 at 23:24
  • react strongly recommends to compose rather than inherit – Joey Baruch Oct 19 '20 at 18:48
  • @JoeyBaruch I agree. See `Update (Nov 2019)` – Robin Oct 19 '20 at 18:50
  • Thanks for your answer, I found it very useful. Just have a quick short question, why do you put a `render={undefined}` on your redirect component? I am a little confused, thanks! – ysong4 Jan 07 '21 at 02:59
  • @ysong4: The reason is, that we are spreading `this.props` which can contain a `render` prop and we want to get rid of this in that case. – Robin Jan 07 '21 at 06:19
8

You can still use the SFC form, which I find a little cleaner. Just mix in any props you need with the RouteProps:

const PrivateRoute: React.SFC<RouteProps> = ({
  component: Component,
  ...rest
}: {
  component: React.ComponentType<RouteProps>;
}) => (
  <Route
    {...rest}
    render={props =>
      fakeAuth.isAuthenticated 
        ? <Component {...props} /> 
        : <Redirect to="/login" />
    }
  />
);
Hunter McMillen
  • 52,839
  • 21
  • 105
  • 154
4

My PrivateRoute

import React from 'react'
import {Redirect, Route, RouteProps} from 'react-router'

export interface IPrivateRouteProps extends RouteProps {
  isAuth: boolean // is authenticate route
  redirectPath: string // redirect path if don't authenticate route
}

const PrivateRoute: React.FC<IPrivateRouteProps> = (props) => {
   return props.isAuth ? (
    <Route {...props} component={props.component} render={undefined} />
  ) : (
    <Redirect to={{pathname: props.redirectPath}} />
  )
}

export default PrivateRoute

Using

<PrivateRoute isAuth={false} redirectPath="/login" path="/t1">
  <Pages.Profile /> your`s protected page
</PrivateRoute>
George
  • 41
  • 1
0

This really helped me

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;

Source: https://medium.com/octopus-wealth/authenticated-routing-with-react-react-router-redux-typescript-677ed49d4bd6

41 72 6c
  • 1,243
  • 4
  • 12
  • 22