React native URLSearchParams
- Published
- Reading time
- 1 min read
- Length
- 205 words
React Native URLSearchParams#
If you're working with React Native and want to handle URL query parameters, you can use the URLSearchParams API. This API allows you to easily manipulate the query string of a URL, including adding or removing parameters, and encoding or decoding values.
Here's an example of how to use URLSearchParams in React Native:
// Create a new instance of URLSearchParams and pass in the query string
const params = new URLSearchParams('?param1=value1¶m2=value2');
// Get the value of a parameter
const param1Value = params.get('param1');
console.log(param1Value); // Output: "value1"
// Set the value of a parameter
params.set('param1', 'newValue');
console.log(params.toString()); // Output: "param1=newValue¶m2=value2"You can also use URLSearchParams to handle arrays and objects as query parameters. Here are some examples:
// Arrays
const params = new URLSearchParams('?colors=red&colors=green&colors=blue');
console.log(params.getAll('colors')); // Output: ["red", "green", "blue"]
// Objects
const params = new URLSearchParams('?user[name]=John&user[age]=30');
console.log(params.get('user[name]')); // Output: "John"Overall, URLSearchParams is a powerful and flexible API for handling query parameters in React Native. Whether you're working with simple key-value pairs or complex objects and arrays, this API makes it easy to manipulate and encode your data.