Implement Autocomplete Feature in React

Michael Tong
Dec 13, 2020 · 5 min read
Image for post
Image for post
Photo by Halacious on Unsplash

You have probably typed something in a google search bar and see suggestions coming up before you finish typing?

Yes, it is common these days but imagine not having the functionality in place? Won’t it be annoying to finish typing a key term that you know you will be using multiple times.

In this article, we will be talking about on how to implement the autocomplete feature in react.

To understand how to implement this, here are key components to remember:

  • understand condition that hide/show autocomplete
  • understand how to scroll on autocomplete items as user press up and down to search for the autocomplete item they are looking for
  • there are a few variables to track: one being the index of autocomplete suggestion, a variable dictating whether to show the suggestion or not, the input textfield, and the filtered autocomplete selections depending on what you type for your textfield.

To get a sense of how it looks like, let’s take a look at how the autocomplete would look like:

Image for post
Image for post

when user types a character or a string, if any of the items in the available suggestions contains the input given, it will display autocomplete.

Sounds simple, right?

Let’s take a look at the implementation:

Okay, before you stress out about how long this file is and exactly what is happening, let me break this into chunks. Let us take a look at the render function first:

Over we have filteredSuggestions, which is calculated as a filtered array when the user starting typing words on the textfield. In the render function, we generate an input textfield that handles when the user types in keywords via onChange.

It also has functionality to handle keypress on enter, up and down when the user scrolls on autocomplete items, via onKeyDown. Furthermore, we also render suggestions only when user puts something in the input and when at least one autocomplete option includes the typed in input.

We just covered what happens in general for different functionalities of autocomplete. But what actually happens in detail when the functions get triggered? Let’s take a closer look at this.setSearchBarValue:

Here we take in e.currentTarget.value, which is whatever value is typed into the <input>. If there are no inputs, then we set itemRefs.current to an empty array. I will discuss later as to what this is used for.

Afterward, we take whatever suggestions is available(passed in as an array props), we filter these suggestions base on which suggestion include the value that was inputted in. Afterward, we set filteredSuggestions, userInput and the autocomplete to be displayed, if there were any suggestions after filtering.

Nothing too complicated right? Let’s take a look what happens when the user goes up and down searching for a different autocomplete option to select:

When the user selects any key from the keyboard, this function gets triggered. The suggestRowIdx is initially set to 0. Here, if the user press enter, which has a keycode value of 13, the first autocomplete option is selected as a text.

If the user presses the up arrow key, which contains a key code value of 38, we only set the new suggestRowIndex if we are already not at the topmost item as we are scrolling up on our list.

Vice versa, if we are pressing the down arrow key, which contains a key code value of 40 if the autocomplete index we are selecting is not at the end of the autocomplete list, then we increment suggest row index by 1.

Notice again we are referring to itemRefs again. What does this.itemRefs.current[scrollIndex].scrollIntoView() mean?

Before understand what the statement means, let’s understand what a ref is in react.

A ref provides a quick way to access dom nodes or react elements in the render method. In our case, it give us access to direct behaviors that we can manipulate with the autocomplete items in the component itself.

In our code, (which I will demonstrate in this.renderComponents later) when we generate the jsx for each child autocompletion section, we store them into refs in our local state.

Image for post
Image for post
Photo by Evan Dennis on Unsplash

Why do we need refs when we can manipulate autocomplete behaviors just with react state and keypress listener functions?

Let’s say we keep scrolling down the list, as shown in the below image:

Image for post
Image for post

With our css, we fixated to a particular height value and we have our overflow-Y set to auto, allowing the scrollbar to show up. But what ends up happening is as we press the down key the autocomplete options don’t actually show up.

In reality, the autocomplete options that are underneath the ones we see will be selected but it won’t display. What? Why?

Because we set a maxheight and overflow of y, what happens is anything within the maxheight will display but the rest of the options will just overflow and won’t show unless the user clicks on the scroll bar.

Enters react refs(or we call itemRefs in this case).

To understand how we store refs of autocomplete options, let’s take a look at renderSuggestion works.

When we render autocomplete suggestions, we generate separate autocomplete sections where we allow user to select. Inside all the <li>s that are generated, that’s where we store our refs locally to itemRefs. These refs are html dom nodes that we can have access to and scroll to as the user scrolls up and down.

Now let’s have a glance at the css part of this:

Here, we have suggestions css, where we set our border, a maxheight that dictates how much suggestions we show at a time, and of course encapsulating it in a scrollbar via the overflow property.

We also set rules for the child text/containers of the autocomplete container itself, with hover colors and padding properties.

Let’s take a look at how you can create an autocomplete component:

That’s it! You just learned how to create autocomplete from scratch.

Michael Tong

Written by

Coding is nothing but a renovation of ideas through fundamental concepts. Stay sharp and stay hungry to learn!

The Startup

Medium's largest active publication, followed by +773K people. Follow to join our community.

Michael Tong

Written by

Coding is nothing but a renovation of ideas through fundamental concepts. Stay sharp and stay hungry to learn!

The Startup

Medium's largest active publication, followed by +773K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store