Tahnik Mustasin
Tahnik Mustasin

Reputation: 2286

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

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?

Upvotes: 15

Views: 12594

Answers (1)

Tyler McGinnis
Tyler McGinnis

Reputation: 35276

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)

Upvotes: 32

Related Questions