3

Cannot seem to find much quality documentation on this. React Router v4 documentation has information of the 'history' object but states that it is mutable and should not be changed. Many examples I have seen seem like 'hacks'. Any insight would be appreciated.

David N
  • 71
  • 1
  • 5
  • This has already been answered here http://stackoverflow.com/questions/42672842/how-to-get-history-on-react-router-v4. Hope that helps. – Todd Chaffee Apr 07 '17 at 17:14
  • @ToddChaffee Ah I see. It seems it is okay to push new route on the history but not trust the location property of the history object since it is mutable. Thanks! – David N Apr 07 '17 at 17:21
  • Yes, what you said. Pushing a new route using the history object works fine in my experience. – Todd Chaffee Apr 07 '17 at 17:40

1 Answers1

0

I had to grapple with this one for a while as a react newbie myself. While the link that @ToddChaffee provided gives you a good insight, this thread highlights that the history object is automatically passed as a prop when you have <Router/> as the top level component. That makes it much simpler than loading the history object separately and using the createBrowserHistory() method.

The following worked for me:

<Route exact path='/' render={({history}) => 
  <Home infoHandler={this.handleUserInfo} 
    imageHandler={this.handleImage} 
    history={history}/>
}/>

Then inside the component you can:

this.props.history.push('/routeYouWantToGoTo');

Don't forget to typecheck the prop in you component before you export the module:

Home.propTypes = {
  history: React.PropTypes.object
}

export default Home;
Community
  • 1
  • 1
Julio Gudiño
  • 181
  • 1
  • 9