React-router: Include the current route in withRouter() or have a withRoute() HOC

Created on 18 Aug 2016  路  4Comments  路  Source: ReactTraining/react-router

I'm currently using withRouter() to create a form wrapper to prevent navigation if the form has unsaved content. I'm using setRouteLeaveHook to do this, which I am getting from the router that withRouter gives me. Unfortunately setRouteLeaveHook needs the current route, which I don't think I can get from the router object I'm passed.

There are some other ways to get the route, but it would reduce complexity if withRouter/another function provided everything I needed.

Most helpful comment

Apparently you can use

this.props.router.setRouteLeaveHook(
  this.props.routes[this.props.routes.length - 1],
  this.routerWillLeave.bind(this)
)

It doesn't look nice, but works.

All 4 comments

We'll get this more or less for free once we get https://github.com/reactjs/react-router/issues/2172. Can't really get it at all until then.

@CLowbrow

There are some other ways to get the route, but it would reduce complexity if withRouter/another function provided everything I needed.

What are the other ways you found out to be able to use this.props.route?

@pierot Passing it through the component tree IIRC.

Apparently you can use

this.props.router.setRouteLeaveHook(
  this.props.routes[this.props.routes.length - 1],
  this.routerWillLeave.bind(this)
)

It doesn't look nice, but works.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ryansobol picture ryansobol  路  3Comments

andrewpillar picture andrewpillar  路  3Comments

misterwilliam picture misterwilliam  路  3Comments

Waquo picture Waquo  路  3Comments

davetgreen picture davetgreen  路  3Comments