6

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?

Felix
  • 166
  • 1
  • 4
  • 20
  • Does this answer your question? [React - How to get parameter value from query string](https://stackoverflow.com/questions/35352638/react-how-to-get-parameter-value-from-query-string) – Michael Freidgeim Feb 18 '20 at 21:23

2 Answers2

13

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>)} />
Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
  • Thanks, this worked. I actually tried that before but it didn't work because of a custom `PrivateRoute` component that I built myself and where I didn't pass the props to the render function. – Felix Jun 14 '18 at 10:38
1

You can use location.search to get that query string in the URL, and get the path from location.pathname

<Route
      path="/about"
      render={({ location, history }) => (
           <div>
                 <p>We are at: {location.pathname}</p>
                 <p>Query string is: {location.search}</p>
           </div>
      )}
/>
Albert Gao
  • 3,653
  • 6
  • 40
  • 69