Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse query string in react-router v4

In react-router v3 I could access it with props.location.query.foo (if the current location was ?foo=bar)

In [email protected] props.location only has props.location.search with is a string like ?foo=bar&other=thing.

Perhaps I need to manually parse and deconstruct that string to find the value for foo or other.

Screenshot of console.log(this.props): enter image description here (Note how from ?artist=band here I'd like to get the value from artist which is the value band)

like image 769
Peter Bengtsson Avatar asked Mar 17 '17 16:03

Peter Bengtsson


People also ask

How do I get query string in React router?

Get a single Query String value location.search object: import React from 'react'; import { useSearchParams } from 'react-router-dom'; const Users = () => { const [searchParams] = useSearchParams(); console. log(searchParams); // ▶ URLSearchParams {} return <div>Users</div>; };

How do you pass a query parameter in React router?

To pass in query parameters, we just add them to the Link s to props as usual. For example, we can write the following: We first defined the useQuery Hook to get the query parameters of the URL via the URLSearchParams constructor. We get the useLocation() s search property.


2 Answers

Looks like you already assumed correct. 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. The one you mentioned has worked great for me so far.

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 search = props.location.search; // could be '?foo=bar' const params = new URLSearchParams(search); const foo = params.get('foo'); // bar 

You can read more about the decision here

like image 169
Tyler McGinnis Avatar answered Sep 20 '22 08:09

Tyler McGinnis


I proffer my little ES6 shape function, awesome, light weight and useful:

getQueryStringParams = query => {     return query         ? (/^[?#]/.test(query) ? query.slice(1) : query)             .split('&')             .reduce((params, param) => {                     let [key, value] = param.split('=');                     params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';                     return params;                 }, {}             )         : {} }; 

Every thing is here, hope to help you.

like image 28
AmerllicA Avatar answered Sep 20 '22 08:09

AmerllicA