Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Parse URL to get Query Variable

Tags:

react-native

Looking for a way to parse a URL to get a query variable in React Native received from Linking.

I'm receiving the URL as something like:

url-app-scheme://somePage?someVar=someVal

I'd like to get the someVar value from the URL.

Any thoughts?

like image 626
Matt K Avatar asked May 18 '17 03:05

Matt K


People also ask

How do I get query params from URL in React Native?

To get the query parameter from a above url, we can use the useLocation() hook in react router v5. In the above code, we first imported the useLocation() hook from the react-router-dom package and invoked it inside the Items functional component then we parsed the query param data using the new URLSearchParams().

How get value from URL in React Native?

In React Native, you can request data from an API over the network using the fetch() method. The syntax is simple as follows: fetch('https://examples.com/data.json'); We simply pass the URL to the fetch method to make a request.

How do I pass query string in React Native?

const getQueryString = (queries) => { return Object. keys(queries). reduce((result, key) => { return [... result, `${encodeURIComponent(key)}=${encodeURIComponent(queries[key])}`] }, []).


2 Answers

This should do the trick

var url = "http://example.com?myVar=test&otherVariable=someData&number=123"

var regex = /[?&]([^=#]+)=([^&#]*)/g,
  params = {},
  match;
while (match = regex.exec(url)) {
  params[match[1]] = match[2];
}
console.log(params)
like image 148
Ray Avatar answered Oct 09 '22 04:10

Ray


There is a URL class in JavaScript which is intended to let you both build and parse URLs robustly, making query parameters easily accessible:

const url = new URL('url-app-scheme://somePage?someVar=someVal');
url.searchParams.get('someVar')

Sadly, the implementation of URL in React Native is not complete and has some known bugs. Fortunately, there is a solid polyfill library called react-native-url-polyfill which provides an implementation of URL that is well behaved and tested - I highly recommend it.

like image 26
lukewarm Avatar answered Oct 09 '22 03:10

lukewarm