React Router issue when using with typescript

Viewed 184

I am using typescript and react-router (5.2.0)

I have a component that requires a match param (id)

import React, { useEffect, useState } from 'react'
import { RouteComponentProps } from 'react-router-dom'

import users from '../../data/users'

type ShowParams = { id: string }

function Show(props: RouteComponentProps<ShowParams>) {
    const id = props.match.params.id
   return <div>{id}</div>
}

export default Show

This works fine when templating RouteComponentProps but this causes problems with the route declaration Once I define the props in Show properly, the route declaration shows an error on the component

<Route path="/companies/:id" exact={true}  component={ShowCompany} />
  Overload 1 of 2, '(props: Readonly<RouteProps>): Route<RouteProps>', gave the following error.
    Type '(props: RouteComponentProps<ShowParams, StaticContext, PoorMansUnknown>) => Element | undefined' is not assignable to type 'ComponentClass<any, any> | FunctionComponent<any> | ComponentClass<RouteComponentProps<any, StaticContext, PoorMansUnknown>, any> | FunctionComponent<...> | undefined'.
 Type 'Element | undefined' is not assignable to type 'ReactElement<any, any> | null'.
          Type 'undefined' is not assignable to type 'ReactElement<any, any> | null'.
  Overload 2 of 2, '(props: RouteProps, context?: any): Route<RouteProps>', gave the following error.
    Type '(props: RouteComponentProps<ShowParams, StaticContext, PoorMansUnknown>) => Element | undefined' is not assignable to type 'ComponentClass<any, any> | FunctionComponent<any> | ComponentClass<RouteComponentProps<any, StaticContext, PoorMansUnknown>, any> | FunctionComponent<...> | undefined'.
      Type '(props: RouteComponentProps<ShowParams, StaticContext, PoorMansUnknown>) => Element | undefined' is not assignable to type 'FunctionComponent<any>'.  TS2769

which makes perfect sense since it can no longer just render the component without the props declaration

How do I declare the props type in routes.

0 Answers
Related