27

I am trying to set a Route path with a query string. Something in the lines of:

www.mywebsite.com/results?query1=:query1&query2=:query2&query3=:query3

I would than transition to the "Results" component like so:

<Route path="/" component={Main}>
  <IndexRoute component={Home} />
  <Route path="results?query1=:query1&query2=:query2&query3=:query3"
    component={SearchResults} />
</Route>

In the SearchResults container I would like to be able to have access do query1, query2 and query3 params.

I have not been able to make it work. I get the following error:

bundle.js:22627 Warning: [react-router] Location "/results?query1=1&query2=2&query3=3" did not match any routes

I tried following the steps in the following guide: (Section: What about query string parameters?) https://www.themarketingtechnologist.co/react-router-an-introduction/

Can I get some help here?

2 Answers 2

25

If you are using React Router v2.xx, you can access the query parameters via the location.query object passed in to your Route component.

In other words, you could rework your route to look like the following:

<Route path="results" component={SearchResults} />

And then inside your SearchResults component, use this.props.location.query.query1 (similar for query2 and query3) to access the query parameter values.

EDIT: This is still the case for React Router v3.xx.

Sign up to request clarification or add additional context in comments.

Comments

24

If you're using React Router >= v4 location.query is not available anymore. You can plug-in an external library (like https://www.npmjs.com/package/query-string), or use something like this:

const search = props.location.search; // could be '?foo=bar'
const params = new URLSearchParams(search);
const foo = params.get('foo'); // bar

(just keep in mind that URLSearchParams() is not supported by Internet Explorer)

3 Comments

Thanks for the heads up about URLSearchParams() and IE
Also note that if you are using create-react-app you must use query-string v5 - npm install query-string@5
Note that you can use this same approach if you're using function components with the useLocation hook: const {search} = useLocation() and the rest of the code works perfectly :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.