Home > front end >  React Router props: what is the correct type?
React Router props: what is the correct type?

Time:02-03

I create a router custom component to do a redirect in case some parameters are not present:

const StateParamRoute = (props: any) => {
  ...
  return stateParam ? <Route {...props} /> : <Redirect to="/error" />;
};

Then, I use it as:

<BrowserRouter>
  <Switch>
    <StateParamRoute path="/" exact component={TestScreen} />
  </Switch>
</BrowserRouter>

But I am getting a warning in the console saying:

Line 48:23:  Unexpected any. Specify a different type  @typescript-eslint/no-explicit-any

I know I can ignore this, or disable the checking on eslint config, but I would like to solve it.

I have tried:

type CustomRouterProps = {
  path: string,
  exact: boolean,
  component: React.ReactNode
}

const StateParamRoute = (props: CustomRouterProps) => {
...
}

But it does not work...

CodePudding user response:

Why don't you just use the types from @types/react-router-dom and import it like so:

import { RouteProps } from 'react-router-dom';

const StateParamRoute = (props: RouteProps) => {
...
}

CodePudding user response:

So far I found if I do:

type CustomRouterProps = {
  path: string;
  exact: boolean;
  component: ComponentType<ReactNode>;
};

const StateParamRoute = (props: CustomRouterProps) => {
...
}

The warning is gone, but I am not sure if it is the best solution.

  •  Tags:  
  • Related