How to access history object outside <Route /> in React Router v4

Tahnik Mustasin picture Tahnik Mustasin · Mar 4, 2017 · Viewed 10.6k times · Source

I have this following code:

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'


const Routes = () => (
  <Router basename="/blog">
    <div>
      <Header />
      <Route exact path="/" component={Main}/>
      <Route path="/article/:id" component={ArticleView}/>
    </div>
  </Router>
)

I can access history or match via props in the Main and ArticleView component. But I cannot access it in the <Header />. Is there a way to get the history object in the Header component?

Answer

Tyler McGinnis picture Tyler McGinnis · Mar 4, 2017

You can use the withRouter HOC for this.

Where your Header component is defined, wrapping the export in a withRouter invocation like below will give your Header component access to match, location, and history

import {withRouter} from 'react-router'

class Header extends Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }
  render () {
    const { match, location, history } = this.props

    return <h2>The Header</h2>
  }
}

export default withRouter(Header)