this is a quick question but I haven't found a solution so far:
I want to access the URL parameter with react-router v4 using the render method. Everything I found so far was only passing the component like this:
<Route path="/:id" component={Child} />
But I want to use the render method like this:
<Route path="/:id" render={() => (<Wrapper> <Child /> </Wrapper>)} />
However, the match
prop is undefined when I try to access the id
parameter with props.match.params.id
in my Child
component.
Any idea how I could use a render function and still access the url parameter?
Here's an example custom withRouter HOC: const withRouter = WrappedComponent => props => { const params = useParams(); // etc... other react-router-dom v6 hooks return ( <WrappedComponent {... props} params={params} // etc... /> ); };
To get the query parameter from a above url, we can use the useLocation() hook in react router v5. In the above code, we first imported the useLocation() hook from the react-router-dom package and invoked it inside the Items functional component then we parsed the query param data using the new URLSearchParams().
Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location. pathname .
You need to pass down props from Route
to Child
:
<Route path="/:id" render={(props) => (<Wrapper> <Child {...props} /> </Wrapper>)} />
or :
<Route path="/:id" render={(props) => (<Wrapper> <Child id={props.match.params.id} /> </Wrapper>)} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With