Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to declare react-router argument as in TypeScript

I'm trying to get set up with react-router using Typescript in a way which accepts a parameter.

In my render element I have

<Route path="/show/:id" component={TestComp} />

And I define TestComp as

const TestComp = ({ match }) => (
    <div>
        <h2>Showing specified ID: {match.params.id}</h2>
    </div>
)

However, VS Code underlines the match parameter (in the declaration of TestComp) and tells me

Binding element 'match' implicitly has an 'any' type.

and it fails to compile.

Can anyone tell me as what type match should be declared? I've tried RouteProps but that doesn't work either. Looking in the index.d.ts, I think it's defined as match<P> but I'm not sure how to declare a parameter as being of a generic type.

UPDATE
Based on the comments to @TarasPolovyi's answer, I've added the following:

enter image description here

As you can see, this still has problems.

like image 558
awj Avatar asked Nov 06 '17 10:11

awj


People also ask

What is router in TypeScript?

Implementing React Router v6 with code splitting in a React Typescript project. React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.

How do I use useParams in TypeScript?

In order to useParams you need to implement a generic for useParams. Building on my example above, I need to type the id . type QuizParams = { id: string; }; // In order to implement that, I'd apply my type to the hook when calling it. const { id } = useParams<QuizParams>();


2 Answers

If you are using react-router v4 then import RouteComponentProps from react-router-dom and use type RouteComponentProps<RouteInfo> - the argument name must be a match

like image 90
Mahesh Bhuva Avatar answered Oct 03 '22 03:10

Mahesh Bhuva


If you are using Typescript and React Router V 4.0 then the syntax is different. You declare your Route as following:

<Route path="/home/:topic?" render={() => {
   return this.renderView(<ContentHolder />);
}} />

Then the Component is declared as following:

interface RouteInfo {
    topic: string;
}

interface ComponentProps extends RouteComponentProps<RouteInfo> {
}

class ContentHolder extends Component<ComponentProps> {

    render() {
        return (
            <Content>
                <h1 className="page-title">{this.props.match.params.topic}</h1>
            </Content>
        );
    };
};

export default withRouter(ContentHolder);

Then inside your this.props.match.params you get fully IntelliSense in both VS Code and IntelliJ

like image 35
Raffaeu Avatar answered Oct 03 '22 03:10

Raffaeu