How to get query parameters in react-router v4

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.


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


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'));
}

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;

  • https://reacttraining.com/react-router/web/example/query-parameters
  • https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams