What is withRouter for in react-router-dom?

When you include a main page component in your app, it is often wrapped in a <Route> component like this:

<Route path="/movies" component={MoviesIndex} />

By doing this, the MoviesIndex component has access to this.props.history so it can redirect the user with this.props.history.push.

Some components (commonly a header component) appear on every page, so are not wrapped in a <Route>:

render() {
  return (<Header />);
}

This means the header cannot redirect the user.

To get around this problem, the header component can be wrapped in a withRouter function, either when it is exported:

export default withRouter(Header)

This gives the Header component access to this.props.history, which means the header can now redirect the user.


withRouter is a higher order component that will pass closest route's match, current location, and history props to the wrapped component whenever it renders. simply it connects component to the router.

Not all components, especially the shared components, will have the access to such router's props. Inside its wrapped components, you would be able to access location prop and get more information like location.pathname or redirect the user to different url using this.props.history.push.

Here's a complete example from their github page:

import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

More information could be found here.