DEV Community

RR Joson
RR Joson

Posted on

A better way to add URL params

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)

Collapse
 
aminnairi profile image
Amin

Hi there, interesting article, thanks for sharing!

Did you know that there is a native object to handle url queries in JavaScript (Browser)?

"use strict";

const urlSearchParams = new URLSearchParams();

urlSearchParams.append("color", "yellow");
urlSearchParams.append("form", "circle");
urlSearchParams.append("keywords", "young kids playground");

console.log(urlSearchParams.toString());
// color=yellow&form=circle&keyword=young+kids+playground
Collapse
 
rrjoson profile image
RR Joson

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