Let's say you are building a filter component for a search page. To achieve this, you might use template strings to build you url params.
const urlParams = `?checkin=${filter.values.checkin}&checkout=${filter.values.checkout}`;
This might look ok but it can get a bit difficult to read when it gets more values.
An alternative way is to use query-string. It provides a stringify function that allows you to pass an object and it generates the url params for you.
import queryString from 'query-string';
const urlParams = queryString.stringify({
checkin: filter.value.checkin,
checkout: filter.value.checkout
})
The result is a way of generating your URL params without having to manually add &. It is also easier to read when you have to pass multiple values.
Top comments (2)
Hi there, interesting article, thanks for sharing!
Did you know that there is a native object to handle url queries in JavaScript (Browser)?
Hi Amin!
Yeah, based from caniuse, IE and other Chinese browsers do not support it.
So maybe it depends on your target audience if you'll use
URLSearchParams