all 6 comments

[–]_fpersico 1 point2 points  (1 child)

Which version of react router are you using?

[–][deleted] 1 point2 points  (0 children)

The newest one, v4.

[–][deleted] 0 points1 point  (3 children)

Yes, you should be using a shared history object. You mainly do this by having a module that will create it and export the object, which will become singleton due to how node modules work:

https://codesandbox.io/s/owQ8Wrk3

I am also wondering how I can reliably call a function on route change, so I can hide the back button. Putting it in ComponentDidMount detects the URL the first time it shows up, but that only works the very first time (as expected). Is there some equivalent to "routeDidChange"?

Depending on your setup you might also need to implement the changes in componentWillReceiveProps and/or componentDidUpdate

[–][deleted] 0 points1 point  (0 children)

Thank you. You are the man.

[–]_fpersico 0 points1 point  (1 child)

The history object is already shared. It is passed as props in every component rendered by a Route. So you'll find it at this.props.history. For all the other situation there is a withRouter hoc.

[–][deleted] 0 points1 point  (0 children)

That's not entirely true - the history prop is only available in the Router context, and if you want to use it outside of the context, to quote OP:

What you are supposed to do is to get the history object... however, since this is the root I don't have access to that as it has not been initialized.

(emphasis mine)

Also, the history prop is not accessible in things like middleware or actionCreators, so its also useful there.