Tobi
Tobi

Reputation: 1902

How to access get parameters in react route

I try to get parameters in the URL of my react App in a structured way. I have parameters called id1 and id2 and it's possible to see them like this

console.log("this.props.location.search", this.props.location.search)

The URL with the parameters will be linked like this

<a href="compare/?id1=6bf45ef0-962e-11e9-923e-972a9f2b848f&amp;id2=58e82e60-961d-11e9-ae32-47571549c9a2">
    <button class="ui yellow button">
       Comparison
    </button>
</a>

I found solutions like

this.props.location.query.id1

this.props.match.params

but this.props.match.params are empty and this.props.location.query does not exist

In addition I tested to set some things in the route. But the following crashes the whole app just showing an empty screen

      <Route exact path="/compare(/:id1)(/:id2)" component={Compare} />

If I do

      <Route exact path="/compare/:id1?/:id2?" component={Compare} />

the App is running again showing the parameters as undefined

match:
  isExact: true
  params:
    id1: undefined
    id2: undefined

Upvotes: 0

Views: 195

Answers (1)

AxelJunes
AxelJunes

Reputation: 656

I think the problem is that you're mixing your url parameters with your query string.

In your href you should have something like this:

<a href="compare/6bf45ef0-962e-11e9-923e-972a9f2b848f/58e82e60-961d-11e9-ae32-47571549c9a2">
  <button class="ui yellow button">
      Comparison
  </button>
</a>

Your route will look like this:

<Route exact path="/compare/:id1/:id2" component={Compare} />

In your Compare component you will be able to access your parameters with this.props.match.params.id1 and this.props.match.params.id2 and make the request to the server that will make the comparison with your query string.

Try it out and let me know if it helps.

Upvotes: 1

Related Questions