1
votes

I am working on a React with typescript app and would like to prevent some pages to be accessed for non authenticated users.

So far I have this:

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

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

export const ProtectedRoute = (props: ProtectedRouteProps) => {
  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

For some reason Typescript throws some compile errors at these lines:

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

Redirect shows: (alias) class Redirect import Redirect Parsing error: '>' expected.

redirectPath shows: const redirectPath: any Binding element 'redirectPath' implicitly has an 'any' type

Route in else stm shows: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362)

update: my package.json does not have react-router but has react-router-dom might this be problem?

1

1 Answers

0
votes

Is your file named ProtectedRoute.ts or ProtectedRoute.tsx? I tried running your code and when I renamed my file with .tsx file type the errors dissapeared.

R.e. package.json react-router-dom is the correct package you need. react-router is used under the hood of react-router-dom.

Also make sure you use npm i @types/react-router-dom