Categories
TypeScript Answers

How to use react-router-dom with TypeScript?

Spread the love

Sometimes, we want to use react-router-dom with TypeScript.

In this article, we’ll look at how to use react-router-dom with TypeScript.

How to use react-router-dom with TypeScript?

To use react-router-dom with TypeScript, we can create an interface that extends RouteComponentProps.

For instance, we write

type RouteParams = {
  id: string;
};

interface Props
  extends RouteComponentProps<RouteParams>,
    React.Props<RouteParams> {}

type State = {
  players: Array<Player>;
};

export class PlayersContainer extends React.Component<Props, State> {}

to create the RouteParams type with the route parameter properties and types.

Tben we create the Props interface that extends the RouteComponentProps<RouteParams> interface and React.Props<RouteParams>.

RouteComponentProps is provided by react-router-dom.

And then we create another type for our component’s State.

Next, we make our component extend React.Component<Props, State> so the props and state types will be correct in our component.

Conclusion

To use react-router-dom with TypeScript, we can create an interface that extends RouteComponentProps.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.