How to deal with query strings and React

Part of what I struggle with when moving from one project to another is to be able to carry over the acquired knowledge. Creating products is a learning process. With the goal of becoming more efficient at it, documenting the learnings has proven to be a good way of improving it. In order to do so, I am just gonna do a quick whizz around how to deal with query strings when working with react.

Dear future self, this is the best way to parse query string parameters with react. They are extensions of the URL, attached at the end of it, after a "?" sign, followed by parameters. Why do we need to handle the query string parameters? They are used to pass data to that specific page (URL), letting us trigger different actions based on what data is passed. Common use cases are interactions with APIs, query data (of course), pagination, assigning attribution to marketing campaigns or filtering.

http://example.com/path?name=Donald&position=President&location=usa

In javascript, we can get the full query string via the window.location.search. In applications using React Router, within the location object passed to components rendered, there is a search object, that contains the query string parameters.

console.log(this.props.location.search) 
// -> '?name=Donald&position=President&location=usa'

Once we have it, we only need a library to parse the values. I use the npm package query-string. We only need to import it to our project and process the values.

The library will generate an object with the values as follow:

const queryString = require('query-string');

console.log(this.props.location.search) 
// -> '?name=Donald&position=President&location=usa'

const parsed = queryString.parse(this.props.location.search);
console.log(parsed);
//=> {name: 'Donald', position: 'President', location: 'usa'}

Did you find it useful? I hope so!

About this blog

In these articles, we review the concepts and processes that we think might be relevant for our customers, as well as our day to day thoughts. They might be useful for anyone using our SaaS customer churn solution or any reader working in the different tangential areas, considering how can they improve their business. If you have topics you'd like for us to cover, just drop me a line. I'll be more than happy to bring them to the blog.

Remember, no amount of surprise and magic will fix a broken experience or a low-value proposition. But a bit of magic added to a good value proposition can transform a somehow normal experience into something highly delightful. there is power in that.