React router v4 programmatically reroute

Seems like there is no quality documentation to be found. The React Router v4 documentation contains information about the history object, but states that it has changed and should not change. A lot of the examples I've seen seem to be "hacks". Any insight would be appreciated.

+3


source to share


1 answer


I had to grab this for a while as a reacting novice myself. While the link provided by @ToddChaffee gives you a good idea, this thread emphasizes that the story object is automatically passed as a prop when you have a <Router/>

component as top level. This makes it much easier to load the history object separately and using the method createBrowserHistory()

.

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 typeheck prop in your component before exporting the module:

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

export default Home;

      

0


source







All Articles