97
votes

I'm using react-router-dom 4.0.0-beta.6 in my project. I have a code like following:

<Route exact path="/home" component={HomePage}/>

And I want to get query params in HomePage component. I've found location.search param, which looks like this: ?key=value, so it is unparsed.

What is the right way to get query params with react-router v4?

11

11 Answers

197
votes

The ability to parse query strings was taken out of V4 because there have been requests over the years to support different implementation. With that, the team decided it would be best for users to decide what that implementation looks like. We recommend importing a query string lib. Here's one that I use

const queryString = require('query-string');

const parsed = queryString.parse(props.location.search);

You can also use new URLSearchParams if you want something native and it works for your needs

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

You can read more about the decision here

18
votes

Another useful approach could be to use the out of the box URLSearchParams like this;

  let { search } = useLocation();

   const query = new URLSearchParams(search);
   const paramField = query.get('field');
   const paramValue = query.get('value');

Clean, readable and doesn't require a module. More info below;

16
votes

The given answer is solid.

If you want to use the qs module instead of query-string (they're about equal in popularity), here is the syntax:

const query = qs.parse(props.location.search, {
  ignoreQueryPrefix: true
})

The ignoreQueryPrefix option is to ignore the leading question mark.

6
votes

The accepted answer works well but if you don't want to install an additional package, you can use this:

getUrlParameter = (name) => {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    let regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    let results = regex.exec(window.location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  };

Given http://www.google.co.in/?key=value

getUrlParameter('key');

will return value

5
votes

I was researching about params for react router v4, and they didn't use it for v4, not like react router v2/3. I'll leave another function - maybe somebody will find it helpful. You only need es6 or plain javascript.

function parseQueryParams(query) {
  //You get a '?key=asdfghjkl1234567890&val=123&val2&val3=other'
  const queryArray = query.split('?')[1].split('&');
  let queryParams = {};
  for (let i = 0; i < queryArray.length; i++) {
    const [key, val] = queryArray[i].split('=');
    queryParams[key] = val ? val : true;
  }
  /* queryParams = 
     {
      key:"asdfghjkl1234567890",
      val:"123",
      val2:true,
      val3:"other"
     }
  */
  return queryParams;
}

Also, this function can be improved

2
votes

Eh?

queryfie(string){
    return string
        .slice(1)
        .split('&')
        .map(q => q.split('='))
        .reduce((a, c) => { a[c[0]] = c[1]; return a; }, {});
}

queryfie(this.props.location.search);
2
votes

According to their docs https://reactrouter.com/web/example/query-parameters you need:

import { useLocation } from 'react-router-dom';

// A custom hook that builds on useLocation to parse
// the query string for you.
function useQuery() {
  return new URLSearchParams(useLocation().search);
}

function App() {
    const query = useQuery();
    console.log(query.get('queryYouAreLookingFor'));
}
0
votes

I just made this so don't need to change the whole code structure(where you use query from redux router store) if you update to react router v4 or higher from a lower version.

https://github.com/saltas888/react-router-query-middleware

0
votes

Here is a way without importing any additional libraries

const queryString = (string) => {
  return string.slice(1).split('&')
    .map((queryParam) => {
      let data = queryParam.split('=')
      return { key: data[0], value: data[1] }
    })
    .reduce((query, data) => {
      query[data.key] = data.value
      return query
    }, {});
}

const paramData = (history && history.location && history.location.search)
                ? parseQueryString(history.location.search)
                : null;
-3
votes

Very easy

just use hook useParams()

Example:

Router:

<Route path="/user/:id" component={UserComponent} />

In your component:

export default function UserComponent() {

  const { id } = useParams();

  return (
    <>{id}</>
  );
}
-4
votes

Without need of any package:

const params = JSON.parse(JSON.stringify(this.props.match.params));

Then you can reach the related parameters with params.id