DEV Community

RR Joson
RR Joson

Posted on

3 2

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️