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?
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().
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.
const getQueryString = (queries) => { return Object. keys(queries). reduce((result, key) => { return [... result, `${encodeURIComponent(key)}=${encodeURIComponent(queries[key])}`] }, []).
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With