TypeScript and React, Part 5

HOC Example: Access the Query String

This is part of this series of blog posts introducing TypeScript and React. Here’s Part 1.

React-router 4 removed the query string parsing feature that was present in past versions. This is a good example of where a React higher order control would make a good substitute. Instead of forcing Components to take dependencies on both the location and a query-string parser, making things hard to test and refactor, it’d be much easier to create a wrapper that does the boring parsing work for you and DRYs out your code.

This follows the TypeScript HOC template I described in the previous post, where a component implements an interface describing the props it expects to be injected (in this case, a “params” object of type any).

query-string was the first query-string parser I came up with via Google:

> yarn add query-string

Here’s a quick example with react-router-dom 4.0.9:

… and some tests:

That one line in the test shows how to wrap a component—normally it would be the default export:

export default withQueryString(MyComponent);

More Reading: