15

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?

1 Answer 1

32

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)
10
  • 5
    I think withRouter only works if the component is part of <Route />. Correct me if I am wrong. Thank you :) Mar 4, 2017 at 22:47
  • 3
    If the component is part of <Route />, there should be no need to use withRouter then. Unless I'm confused. Mar 5, 2017 at 19:58
  • 2
    Hey @Tayler, you're confused haha. My <Header /> is not part of a <Route />. It is inside <Router /> but not <Route />. So I can't access those props from there. Mar 6, 2017 at 13:44
  • 7
    Tyler's answer is correct. You can access to history, match or location by two ways: 1. By withRouter wrapper 2. By passing Header to Route: <Route component={Header} /> Mar 6, 2017 at 19:16
  • 1
    Worked for me. Thanks @TylerMcGinnis
    – blacktone
    Aug 1, 2017 at 0:04

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.