Hamed Minaee
Hamed Minaee

Reputation: 2560

react-router-dom with multiple query strings does not work

I am new to react router. I use react-router-dom 4.2.2 in my router set up I have:

<Route path={"/confirmuser/:confirmation_code/:username"} component={ConfirmUser} />

and here is a sample url I am trying to achieve:

localhost:3003/confirmuser?confirmation_code=986797&username=5f1

As you see I am trying to send multiple query strings. in the confirmUser I read the query strings as follow:

    console.log(this.props.match.params.confirmation_code);
    console.log(this.props.match.params.username);

However I do not even get directed to this component and it seems react is not able to route to that page properly. Any idea?

Upvotes: 0

Views: 3111

Answers (3)

Oblosys
Oblosys

Reputation: 15106

React-router v4 doesn't parse query strings anymore, so you either have to do the parsing yourself (not recommended), or use a package like query-string. An easy way to access the values is with a wrapper component, like this:

import * as queryString from 'query-string';
..

const WrappedConfirmUser = () => {
  const {confirmation_code, username} = queryString.parse(location.search);
  return <ConfirmUser confirmation_code={confirmation_code} username={username}/>;
}

Upvotes: 1

Arkej
Arkej

Reputation: 2251

Your path doesn't match your url.

It matches localhost:3003/confirmuser/986797/5f1

Then you can access params using extra prop match:

{props.match.params.confirmation_code}

{props.match.params.username}

Upvotes: 1

Sander Garretsen
Sander Garretsen

Reputation: 1723

You are trying to map search-params to path segments?

The Route you defined will try to match the path, not the search params. Try: http://localhost:3003/confirmuser/986797/5f1 and the values will be in this.props.match.params like this:

{
  confirmation_code: '986797',
  username: '5f1',
}

if you still want to read the search params, you can access them from this.props.location.search, but react-router will not match them to a route for you.

Upvotes: 1

Related Questions