What Is withRouter And How And When To Use It?

withRouter
You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

Usage of withRouter
If you want that your component will receive Router Props, but don't want to wrap it in <Route component={Some} />. You can just use withRouter function to connect component to the Router, without additional manipulations or jsx tags wrapping. You can just export default withRouter(component)

Explanation/Example
When you include a main page component in your app, it is often wrapped in a component like this:
 <Route path="/movies" component={MoviesIndex} />
By doing this, the MoviesIndex component has access to this.props.history so it can redirect the user with this.props.history.push

Some components (commonly a header component) appear on every page, so are not wrapped in a :
 render() {
   return (<Header />);
 }
This means the header cannot redirect the user.

To get around this problem, the Header component can be wrapped in a withRouter function when it is exported as below:
 export default withRouter(Header)
This gives the Header component access to this.props.history, which means the header can now redirect the user.

Refs: REACT TRAINING / REACT ROUTER / withRouter

Comments

Popular Posts