andrfas
andrfas

Reputation: 1330

How to get query parameters in react-router v4

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?

Upvotes: 107

Views: 150569

Answers (12)

rslj
rslj

Reputation: 380

If your route definition is like this:

<Route exact path="/edit/:id" ...../>

import { useParams } from "react-router";

const { id } = useParams();

console.log(id)

Upvotes: 0

Chilaxathor
Chilaxathor

Reputation: 766

React Router v6

Source: Getting Query Strings (Search Params) in React Router

I know this was a question for v4, but with v6 being released, here is how we can search for params in the new version of React Router.

With the new useSearchParams hook and the .get() method:

const Users = () => {
  const [searchParams] = useSearchParams();
  console.log(searchParams.get('sort')); // 'name'

  return <div>Users</div>;
};

With this approach, you can read one or a few params.

Read more and live demo: Getting Query Strings (Search Params) in React Router

Upvotes: 4

Andrii Starusiev
Andrii Starusiev

Reputation: 7774

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

Upvotes: 10

Stoyan Atanasov
Stoyan Atanasov

Reputation: 66

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;

Upvotes: 0

fisch2
fisch2

Reputation: 2773

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.

Upvotes: 17

CommonSenseCode
CommonSenseCode

Reputation: 25418

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

Upvotes: -4

user10750437
user10750437

Reputation: 405

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;

Upvotes: 28

Faheem
Faheem

Reputation: 1166

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

Upvotes: 2

kartikag01
kartikag01

Reputation: 1579

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

Upvotes: 7

Dimitris Saltaferis
Dimitris Saltaferis

Reputation: 31

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

Upvotes: 0

Tyler McGinnis
Tyler McGinnis

Reputation: 35286

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

Upvotes: 210

Xopsy
Xopsy

Reputation: 101

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

Upvotes: 6

Related Questions