Creating Real-Time Autocompletion With React: The Complete Guide

Ever wondered how autocomplete works?

Francisco Sainz
Mar 13 · 7 min read

React is one powerful Javascript library and using state, we will create a real-time searching with autocompletion.

Before we start, make sure you have npm and create-react-app installed on your computer.

Setting up

Let’s create a new react project using create-react-app

To do so type the following command in the terminal

create-react-app autocomplete

NPM will create everything you need to get you up and running.

Once that’s done, simply cd into our project directory and start the local server using the following commands.

cd autocomplete
npm start

Let’s also create a components folder inside src to keep our project organized and maintainable.

Now that everything is set up, head to src/App.js and delete the header tag.

Convert app into a React Component class.

This component will hold the data we will load into the search component later on. This will be our parent component.

We will use updateField to update the search bar’s input inside our Search Bar component — which we will create later.

Now that our App.js file is ready, we can start implementing the actual search bar with autocomplete.

Let’s start by creating a stateless component called SearchBar.

This component will receive 3 props.

  • Results: Our search logic will be implemented in the parent component and autocomplete results will be passed down as props.
  • updateField: As mentioned above, this function will update the keyword property in App’s state whenever the search’s input changes.
  • keyword: We will pass this property back down into search to update the input when an autocomplete options is clicked.

Updating the Input

keyword value updates real time

To achieve this as seen above we need to update the value of our input as we search to return real-time results using react’s state.

We will use the keyword property in App’s state to keep track of the input’s value as we type or delete.

We can create a function — onSearch — to update the keyword property whenever the input’s value changes. This can be done using onChange and passing the input’s value to our onSearch function.


Matching keyword with data

Result array is updated as values are matched with keyword

We can create a nifty little algorithm to match objects based on their name property — as seen on the gif.

Javascript’s include will return a boolean value if any of the letters in a string match a specific keyword, but there’s a problem with this approach.

Let’s say we search “Andrea”. Include will return true. Great, right? but what if we search for “rea”. Include will return true again. We don’t want that because event though it exists in “Andrea”, no names starting with “rea” exists.

We can solve this another way. Since we know the length of our keyword, we can simply create a substring from the actual name — Andrea —and compare it to the keyword. “Andrea”.substring(0,3) will return “And”. We can set everything to lower case for comparison, and since our keyword is “and”, we know that we got an actual match.

This function will compare a word and a keyword, and check if they match; returning either true or false.

We can implement it inside onSearch() using javascript’s filter function. Filter works by comparing each value in an array against a specified value. If they match, it adds it to a new array. Only the values that match will be included in the new array.

Our matched results will be updated and sent to the result property in the state, the keyword will also be updated.


Rendering Matched Data

Rendering results in real time

We can create a preview component to render all the objects that match our keyword using javascript’s map function.

We need to create a component for every individual result from the array. We will display its Name, Position, and Age properties.

We can then map each of the values in the results array to be rendered with this component individually.


Updating Input Value on Click

input field takes name of clicked person

We can update our search bar’s input value by attaching its value property to the state’s keyword.

<input value={this.state.keyword} ...onChange... />

This way, when the keyword property is updated, so will the input’s value property. This is particularly useful because we want to update the input field when the user clicks on an autocomplete option from the list.

To implement this, we can create a function to update the state whenever a preview component is clicked.

We pass the name property to the updateText(name) to do this. We will also disable the list because our user has selected an item and thus, stopped searching.

updateText = text => {
updateField("keyword", text);
updateField("results", []);
};

We can then pass this function as a prop to SearchPreview and add an onClick event in the outermost div of the component.


Adding a Cancel button

Clearing input on cancel button click

Maybe the user changed his mind and doesn’t want to search anymore. Instead of having to delete everything from the input using backspace to close the autocomplete, we can implement a cancel button.

This will be pretty simple since all that is need is a button that, when clicked, deletes the keyword and clears the results field in state.

Let’s create a function to clear the search input and hide the autocomplete div.

cancelSearch = () => {
updateField("keyword", "");
};

Pretty simple right? All we have to do is update the keyword to be empty onSearch will update the results back in App.js.

Next, let’s add a button with an “x” right above our input inside our render function.

<button onClick={() => cancelSearch()}> x </button>

When we click the button, our search bar’s input will be cleared and results hidden.

Additionally, to improve UX, we can display the cancel button only when the user is searching, and hide it when he isn’t.

className={`cancel-btn ${keyword.length > 0 ? "active" : "inactive" }`}

By adding this class to the button, we can hide it depending on the keyword’s value with CSS opacity.

Finally, we can use translate to position the button at the end of the search bar using CSS.


Updating Visibility

We only want to display the results div whenever there are results to be displayed and will hide it if the keyword is empty (“”) or if there are no results.

We can do this by rendering the results div conditionally based on our search results.

Bonus: Using APIs

rendering stock symbols realtime with an API

Right now, our component will only work the complete data is already loaded into App’s state. This means that we need to either load all the data into the app so we can search it from a local database, or load it from an API.

This is far from ideal. Apart from being highly inefficient if we have millions of objects in our array. Data is usually stored in a server.

Example API

I’ve been developing an app that displays data from a Stock API called FinancialModelingPrep. This API is free and provides an API route to search for Stock Symbols.

We can make the request inside our onSearch to retrieve autocomplete data in real-time.

Using fetch and async / await to retrieve stock Symbols based on input’s keyword.


What about the styling.

If you were following along you are probably wondering how I got the search bar to look like this. Since CSS is not the main focus of this tutorial, you can play around with the existing style I used for this project.

Testing it out yourself

You can find the full GitHub repository here to play around with this implementation yourself.

To get it up and running, either clone or download the project from the GitHub repository above.

Don’t forget to run the following command before running the project to download all the dependencies required for this project.

npm i

I hope this tutorial was useful to you,

Happy Coding.

The Startup

Medium's largest active publication, followed by +606K people.

Francisco Sainz

Written by

Software engineering students with a passion for web design, development and everything else in between.

The Startup

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

More From Medium

More from The Startup

More from The Startup

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade