How to build an autocomplete search component in React and TypeScript
Tags: react, typescript, webdev, programming
Published: 2022-11-06 23:18:50

## How to show suggestions of data from an API Rest

Nowadays, one of the most widely used components of a website is the search engines with autocomplete or suggestions.

It is usually the first component with which the user interacts since it is more practical to perform a search and go directly to what we need. These components are essential in sites such as e-commerce for a good user experience.

In this tutorial, we will build a simple search component that offers users suggestions about what they are typing without third-party libraries.

## What is Autocomplete Search?
_Autocomplete is a pattern used to display query suggestions._

An autocomplete search, also called “predictive search” or “autosuggest,” is a component that the user types in the input field that will suggest various predictions or possible results of how the search might be completed.

Autocomplete works with a search engine that learns and improves the suggested results as it is fed by the searches its users perform.

In this case, we will not see more about search engines because it is out of the scope of the tutorial. If you want to learn more about this topic, you can look at this [site](https://www.addsearch.com/blog/autocomplete-search/). Without further ado, let’s get to programming.

## Setting Up Autocomplete search
We create our application with [vite](https://vitejs.dev/guide/#scaffolding-your-first-vite-project) with the following command:

``` shell
yarn create vite autocomplete-search --template react-ts
```

We install the dependencies that we will need in the project:

``` shell
yarn add @nextui-org/react
```

In this case, I am only going to use a third-party library for the styles you can use whatever you want:

* [nextui](https://nextui.org/) a Javascript/CSS framework

After that, we create the following folder structure for the project:

```
src/
├── components/
│   └── ui/
│       ├── Autocomplete.tsx
│       ├── Autocomplete.tsx
│       ├── index.ts
│       └── ui.module.css
├── hooks/
│   └── useAutocomplete.ts
├── ts/
│   └──interfaces/
│      └── Country.interface.ts
├── App.tsx
└── main.tsx
```

## Components
`AutocompleteWrapper.tsx` This component is only used as a container or wrapper of `Autocomplete.tsx` and is where we are going to request the data we need.

We use the [restcountries](https://restcountries.com/) API for the tutorial and only use English-speaking countries so that the query will be as follows:

```
https://restcountries.com/v3.1/lang/eng
```
`Autocomplete.tsx` This is the main component, and it has two sections. The first section is the input element, and the second is the list of suggestions.

Usually, a `<ul>` or `<ol>` element is used, but in this tutorial, we will use Rows components inside a Next UI Card component.

{% embed https://gist.github.com/ljaviertovar/4d86389aec325607c0fbf6417e05222d.js %}

First, we create the types we need. The API returns us a large amount of data that we will not use, so simplifying the information and the types would look like this:

``` typescript
export type Country = {
  name: Name
  flags: Flags
}
type Name = {
  common: string
}
type Flags = {
  png: string
  svg: string
}
```
After that, we will create the following states:

`searchedValue` — Here, we will store the text user is typing.

`suggestions` — Here, we will store the suggestions that match what the user writes.

`selectedSuggestion` — Here, we will store the option selected by the user.

`activeSuggestion` — Here, we will store the index of the suggestions shown. We will use it to know which suggestion is selected by the keyboard.

Now, we need to create the functions that will react to the events of the input element and the results list.

`handleChange()` This function will be executed every time the user types something in the input element. We’ll validate if what is entered isn’t an empty value. Otherwise, we’ll set the states to their initial values.

If the value received in the input element isn’t empty, the function will be executed and display the suggestions that match the value entered.

`handleClick()` This function will be executed when the user selects a suggestion; we save the selected value and set the remaining states to their initial values.

`handleKeyDown()` This function will be executed when an event is detected on the keyboard, so you can browse through the suggestions and select one.

Finally, we add a `useEffect` to focus on the input element when the component is mounted.

That’s all! We already have an autocomplete search we can use in any project by passing the input reference and the data to filter.

As an additional step and good practice, we will take the functionality to a custom hook, and our component will be cleaner and more readable.

{% embed https://gist.github.com/ljaviertovar/d60264fa84a3becf74a29f6ad25017cc %}

{% embed https://gist.github.com/ljaviertovar/bab3901dc61d69153de079de2f57b64b %}

The app looks like this:

![Autocomplete search](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/scn36vs5nehfmgqum0ga.png)

[**See the demo here**](https://autocomplete-search-react-ts.vercel.app/)

**[Repo here](https://github.com/ljaviertovar/autocomplete-search-react-ts)**

## Conclusion
We have created a simple search component by applying filters to the data received this search could get more and more complicated depending on the case. After capturing the selected value, you could add more functionality, such as displaying the details of the country selected.

I hope this tutorial has been useful for you and that you have learned new things in developing this application.

---
**Read more:**

- [Why Should You Use Cleanup Functions in React’s useEffect Hook?](https://dev.to/ljaviertovar/why-should-you-use-cleanup-functions-in-reacts-useeffect-hook-2g2c)

- [Improve User Experience with a Modern Skeleton Loader in React](https://dev.to/ljaviertovar/how-to-build-a-skeleton-loader-with-react-3k9o)

**Want to Connect?**
Love connecting with friends all around the world on [Twitter](https://twitter.com/ljaviertovar).