Parsing Query Parameters and Fragments

Pritam Pratik Agrawal
2 min readDec 8, 2020

Handling routes in react can be one of the most tedious things in the application; the order of the endpoints and home routes, absolute and relative paths, parsing the params and fragments; specially handling the memory leaks and unnecessary toll on network when we try to load a single page application handling multi page functionality.

Though some of the above issue is remediated with React 16.6+, thanks to code-splitting, we can now use lazy-loading and suspense to only render the component when it is called upon, boosting the dynamicity and speed of application. But, here I’ll strictly be limited only on a tiny functionality of the bigger routes scenario i.e., to parse the query params.

For this, a little background knowledge on react-router-dom and route params is required (example /:id to route to a particular id to fetch its data content). But how do we extract query params (like ?someKey=someValue at the end of URL you usually see)? How do we extract the fragments (#someValue at the end of a URL)?

For Query Params, we can pass it easily like:

<Link to=”/myDefinedPath?key=5">Go to key 5</Link>

or we can use

<Link to={{pathname: ‘/myDefinedPath’, search: ‘?key=5’}}>Go to key 5</Link>

React router makes our task easy in many ways and here it solves it by giving us access to search string: props.location.search

Though above will only give you something like ?key=5. But we want it in a key-value pair and also without ‘?’ and ‘=’. We can extract that by using below when our component mounts when it is rendered:

This URLSearchParams is a built-in object (with Vanilla JS). It returns an object which exposes the entries method. This entries method returns an Iterator — more like a construct which can be used in a for..of.. loop as shown in above snippet.

When looping through queryParam.entries(), we get arrays where the first element is the key name (here ‘key’) and the second element is the assigned value (here ‘5’).

For Fragments, it can be passed like:

<Link to=”/myDefinedPath#startPosition">Go to start position</Link>

or we can use

<Link to={{pathname: ‘/myDefinedPath’, hash: ‘startPosition’}}>Go to start position</Link>

Similarly we can use props.location.hash to access the fragments.

--

--