2
votes

I am trying to get information about the current route on a non-Route component.

React Router provides singleton versions of history (browserHistory and hashHistory) that you can import and use from anywhere in your application.

Previously, it would seem you could use browserHistory, but that no longer appears to be supported. I'm using react-router-redux^4.0.8 and @types\react-router-redux^5.0.1.

How can I access the current route location?

1

1 Answers

2
votes

This is very simple. You can use the withRouter HOC

You can get access to the history object's properties and the closest Route's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

It is used liked this:

import {withRouter} from "react-router-dom"
@withRouter
class NonRouteComponent extends Component {
  render() {
    // you have access to this.props.match
    // you have access to this.props.history
    // you have access to this.props.location
    const { match, location, history } = this.props

    return <h1>Hi {location.pathname}</h1>;
  }
}

If you don't use decorators aka @withRouter you can export the component like so:

class NonRouteComponent extends Component { ... }
export default withRouter(NonRouteComponent);