3

I am using react-router-dom v 5.2.0. I want to add multiple query params in the URL and I'm not sure how to accomplish it. My route looks like this:

<Route path="/admin/users" component={UserList} />

I want to pass multiple query params like...

/admin/users?search=hello&page=1&user_role=admin

Currently I'm doing it manually like...

<Link to="/admin/users?user_role=admin" />

However, with this manual thing I cannot concat multiple query params. Is there a way to concat the query params dynamically? Does react-router-dom has it's own way of doing such things?

Abeid Ahmed
  • 315
  • 1
  • 5
  • 15

2 Answers2

10

You can make use of query-string package to parse queryParams into object which will allow you to edit them easily and then stringify them before you pass them to link.

import qs from 'query-string';

...
const queryParam = qs.parse(location.search);
const newQueryParam = {
   ...queryParam,
   user_role: 'admin',
   something_else: 'something',
}


...
<Link to={{ pathname: '/admin/users', search: qs.stringify(newQueryParam)}} />
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
4

The answer was on the link provided by SMAKSS. The trick was to set the key value pair to the URLSearchParams.

  const addQuery = (key, value) => {
    let pathname = location.pathname;
    // returns path: '/app/books'
    let searchParams = new URLSearchParams(location.search);
    // returns the existing query string: '?type=fiction&author=fahid'
    searchParams.set(key, value);
    history.push({
      pathname: pathname,
      search: searchParams.toString()
    });
  };

... and then you can use like this...

<button onClick={() => addQuery("page", 2)>Page 2</button>
Abeid Ahmed
  • 315
  • 1
  • 5
  • 15