Chris Frewin
1 min readSep 4, 2020

--

For those interested, I struggled for a bit on how to get a TypeScript version of this working. The gotchya is to use a proper type for the Component (I used React.FC since I write basically all my components as functions with hooks) and also extend those props using the 'RouteProps' directly from the react-router-dom library. Note that if the actual prop name 'Component' is not capitalized, TypeScript will rage.

`PrivateRoute.tsx`:

```

import * as React from "react";

import { Redirect, Route, RouteProps } from "react-router-dom";

import { isAuthenticated } from "../../utils/utils";

interface IPrivateRouteProps extends RouteProps {

Component: React.FC;

}

export function PrivateRoute(props: IPrivateRouteProps) {

const { Component, location } = props;

return (

<Route

{...props}

render={(props: any) =>

isAuthenticated() ? (

<Component/>

) : (

<Redirect

to={{

pathname: `/login/redirectUrl/${encodeURIComponent(location?.pathname || '')}`,

}}

/>

)

}

/>

);

}

```

Then you use PrivateRoute like so:

<PrivateRoute path={`/collection/:collectionId(${Constants.guidRegex})`} Component={GuidRouter}/>

See the answers that helped me at:

https://stackoverflow.com/a/37414418/2805387

and:

https://stackoverflow.com/questions/31815633/what-does-the-error-jsx-element-type-does-not-have-any-construct-or-call

--

--

Chris Frewin
Chris Frewin

Written by Chris Frewin

https://wheelscreener.com https://vannacharm.com https://chrisfrew.in 👨‍💻 Software Engineer 🏠 Austria/USA 🍺 Homebrewer ⛷🏃‍ 🚴 Outdoorsman

No responses yet