Reputation: 519
I have the following:
<BrowserRouter>
<Sidebar>
<Switch>
<Route path='room/:roomId' component={RoomComponent}/>
</Switch>
</BrowserRouter>
Now inside the room component, if I console.log(this.props). I have access to the roomId param. However, inside the Sidebar component, I don't have access to the roomId param. If I console.log(this.props), my location and match props look like follows:
location:
hash: ""
key: "6qujt0"
pathname: "/room/asdf3/"
search: ""
state: undefined
match:
isExact: false
params:{}
path: "/"
url: "/"
Do you have any idea, what could be happening? Thank you in advance!
Upvotes: 3
Views: 432
Reputation: 49749
react-router-dom is passing those props :History, Location, Match.
react-router is only going to pass these props down to components that are actually used inside the Route. That is why RoomComponent has access to those props however Sidebar component is not going to access because Sidebar was not setup as a component value for a Route.
Upvotes: 1
Reputation: 5534
You can only access that information within your Route
component
and its further children (if wrapped with withRouter
).
What you could do is use the same matching code that Route
uses with matchPath:
// inside your Sidebar component
import { matchPath } from "react-router";
const match = matchPath(this.props.location.pathname, {
path: "/room/:roomId",
exact: false,
strict: false
});
// match should be:
// {
// isExact: false
// params: {
// roomId: "asdf3"
// }
// path: "/room/:roomId"
// url: "/room/asdf3"
// }
Upvotes: 1
Reputation: 1463
That's because the Sidebar is not the child of the room component, it's sitting outside of the router, it will only get the root path as the closest match.
One solution will be saving the match
object to the redux store and get it through the state.
Upvotes: 0
Reputation: 150
you can define state variable roomId
in your RoomComponent
like
constructor(props){
super(props);
this.state = {
roomid: this.props.params.match.roomId
}
}
and now pass this value to your SidebarComponent
as props so it can access this value.
<SidebarComponent
roomId = this.state.roomid
/>
Upvotes: 1
Reputation: 1014
Probably sidebar component doesn't have withRouter
, but you can better use a function or a library to parse url queries, I'm always using query-string's parse function, here's an example:
import * as qs from 'query-string';
const { search } = history.location;
const query = qs.parse(search, { ignoreQueryPrefix: true });
console.log(query.roomId);
Upvotes: 0