Reputation: 259
I am trying to understand what is the "react" way to access the current application location using react-router (v2.4.0). Prior to the new react-router breaking changes etc, I was able to use
this.context.router.getCurrentLocation()
Now it seems that again I can inject the router into the context of my component, but the router instance itself does not contain api to get anything related to the current location or query parameters, etc. So the logical question popped: "Am i doing this right?".
After some research I found out that react-router's Route component, that I am using, is injecting the location into the properties of the component that is mapped to that route. And that is great! However in my case I have multiple layers of components nested deep inside the master component that is mapped to Route, so: "Am i supposed to pass this.props.location all the way down to the component that will actually need it, or is there a more human way to make it?"
So what is the right way to get current router path, the query parameters and stuff like that, that may be needed in the code? Am I supposed to work with the this.props.router and/or browserHistory objects directly, am I supposed to find a way to propagate this.props.location to where I will need it, or am I missing something in the picture?
Thanks for your time!
Upvotes: 0
Views: 424
Reputation: 2605
It depends a bit on the structure of your application for the approach you will take, but yes this.props.location.query
will contain your query parameters for a given Route component in react-router v2+.
If for instance you visited something like /result?foo=bar&apple=orange
, from your Route component you could find bar
from this.props.location.query.foo
and orange
from this.props.location.query.apple
this.props.params
on the other hand will contain the general dynamic parameters you might map to a route, so for something like /profile/users/:userID
, you could find your userID for the given route in this.props.params.userID
.
You can pass these down as props to any child components that need them just as you would any React component, but you also may want to consider whether those children should be nested routes themselves / have direct access to their own this.props...
from the router, or if the parent is able to handle the logic on it's own before passing them down.
The official docs give some pretty good examples and use cases for building your app, and are worth checking out: https://github.com/reactjs/react-router/blob/master/docs/Introduction.md
Upvotes: 1