A postcode widget in React

Our job is to create beautiful, fast and secure web applications. This postcode widget embodies all three aspects.

The widget is in use on Blitts, one of the products we maintain. Blitts allows you to request a permit for home improvement. Enter your postcode to see if the product is supported in your area. (hint: only Dutch postcodes will work. Try 1234AA 1 for a success response).

To break that down a little, we have a normal HTML form and a chunk of inline jQuery directly after it. It works, but lacks input validation, attaches to $(document).ready, and blocks rendering, amongst many other things we’d all like to avoid.

Let’s get started modernizing it!

React

Since Blitts is a Rails app, step one is to install react-rails, after which we can start writing our components.

echo "gem 'react-rails'" >> Gemfile
bundle
rails g react:install

We’ll replace all of the inline HTML with a react_component, which we’ll also create. For the time being, we move the form into the component, barely changing it:

We’re using controlled components here, meaning React.JS will be in charge of the input values, not the browser. We are going to change all input to uppercase and truncate values where it makes sense. We could go wild here, but we’ll leave it at this.

In earlier attempts, I had abstracted each input into its own component. That way I would have had each validation isolated. Unfortunately I couldn’t figure out how to update the owning component without falling back to the DOM. When I figure out how to decouple the inputs (without resorting to something like flux), I’ll write a new post.

A check in the browser confirms that the validations are working. We’ve already improved the situation! Time to handle the form submission:

First off when postcode and house number aren’t present, we won’t post the form but show a friendly message on screen. Second major improvement in a couple minutes!

When the field values look okay, we can let the ajax request go through. Instead of updating the DOM directly, we’re going to use the component’s state to let React do the work for us. We also start handling error responses. And that’s it!

There is plenty to be improved on the back end, such as moving towards a REST API that returns 404 when a postcode isn’t supported. It would get rid of the if-statement in our handler, making it easier to understand. However we’re not touching the backend now, so we’ll have to live with this.

After this change, our widget renders asynchronously, its code is organized, and offers a much richer experience than before. Not bad.

A big tip of the hat to Hannes Fostie for introducing me to React.JS and showing me how awesome it is. Thanks Hannes!