React Autocomplete Searchbox - Making it accessible (while being easy to style)

Posted on July 21, 2019

The Backstory

Every React project I’ve ever worked on has some type of autocomplete feature requirement. I’ve build a real estate autocomplete input that suggested cities, zipcodes, neighborhoods, school districts, houses, and more all based on what the user typed it. I’ve also built simpler ones that just let the user more easily filter through a list of ~50 preset items.

Generally speaking — I think developers should hold strongly to <select> tags for as longs as possible. They are generally more reliable cross-browser, take less code, are easier to test, and work great on mobile. However, they do have their limits.

And up to this point, I’ve reached for React Select once a more advanced tool was needed.

However, that often leaves you a little disassified. It’s got a highly opinionated design, is rather hard to style, and testing is a bit rough around the edges.


React Downshift

Per their docs —

This is a component that controls user interactions and state for you so you can create autocomplete/dropdown/select/etc. components. It uses a render prop which gives you maximum flexibility with a minimal API because you are responsible for the rendering of everything and you simply apply props to what you’re rendering.

This differs from other solutions which render things for their use case and then expose many options to allow for extensibility resulting in a bigger API that is less flexible as well as making the implementation more complicated and harder to contribute to.

Example Select

As you can see in the sandbox above, the api design exposes the raw label,input, ul, and li. This makes it incredibly easy to position any custom html elements inside and around the select.

Need to break up the returned options and sort them by sub-type? You can easily to that now.

It also more easily fits into any design system because you can continue using tailwind, bootstrap, styled-components, or whatever you use anywhere else. You don’t need to adapt your system for the tool.