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?

1

2 Answers 2

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>)} />
1
  • 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
    Commented Jun 14, 2018 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>
      )}
/>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.