/assets/img/2019-09-10_react_router_1-640.png

Using withRouter in a TypeScript React Component

tl;dr: When combining TypeScript with React, some of the tutorials cannot be adapted that simple.
In this example I show how to use withRouter to manipulate the history in a functional React component.

Contents

When it comes to manually changing the current Route/History in a React application, the component is usually wrapped into the withRouter higher-order component1.

This component provides access to several props (e.g. history and location).

Note: With React Router 5.1 you can also use Hooks for History, Location etc2.

RouteComponentProps

It can be a bit tricky when you try to get this to run using TypeScript with React. First you should install the @types/react-dom-router package to get access to the required types.

Now you can access RouteComponentProps which contains all relevant members:

export interface RouteComponentProps<Params extends { [K in keyof Params]?: string } = {}, C extends StaticContext = StaticContext, S = H.LocationState> {
  history: H.History;
  location: H.Location<S>;
  match: match<Params>;
  staticContext?: C;
}

The following component provides an example, how the RouteComponentProps now can be used inside a functional component:

import * as React from "react";
import {RouteComponentProps, withRouter} from "react-router-dom";

/**
 * Simple example on how to use withRouter / history in a TypeScript React Component
 */
function ReactFormRouteButton({history}: RouteComponentProps): JSX.Element {

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {
        event.preventDefault();
        // do something

        // redirect to new target using Router's History
        history.push("/");
    };

    return <form onSubmit={handleSubmit}>
        <label htmlFor="foo">Foobar</label>
        <input id="foo" name="foo" type="text"/>
        <button>Submit</button>
    </form>
}

export default withRouter(ReactFormRouteButton);

Footnotes

Tags

Comments