Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing URL param in react-router render function

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?

like image 399
Felix Avatar asked Jun 14 '18 10:06

Felix


People also ask

How do you access URL parameters using React router 6?

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... /> ); };

How do I get query params in React router?

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().

How do I find the URL path in React router?

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 .


1 Answers

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>)} />
like image 88
Tomasz Mularczyk Avatar answered Sep 28 '22 10:09

Tomasz Mularczyk