Implement an Autocomplete Component in React

Nacef Otay
eDonec
Published in
2 min readFeb 15, 2021

As a way of enhancing the user experience in your application, auto-complete inputs help you also to avoid spelling issues for sensitive data.

auto-complete search box

So here’s a sample of how to build an auto-complete component in React (in this tutorial, this feature is used for country options).

Requirements

Project dependencies from codesandbox.io

As you can see from the dependencies list, we have chosen styled-components to build our custom input.

  • First, we need to install styled-components library
  • npm install styled-components --save or yarn add styled-components

After installing your dependency, all you need is to import it in your Style.ts so that it lets you write actual CSS for your JSX elements (which are returned as React elements).

This means you can use all the CSS features in your customization.

As an example, a div customization will look like this :

import styled, { css } from "styled-components";export const Root = styled.div`position: relative;width: 320px;`;

Moving to the main goal of this tutorial,

  • First, you should start by creating Data.json which contains the data options to display in your input.
  • Then, building a new functional component Autocomplete.tsx in which we have two useState Hooks from React that will make you initialize the input Textand its corresponding suggestions list while typing and there will the whole feature be built and isComponentVisible for showing the list of suggestions
  • As you can see the code above we have to mention that we used a little trick in order to assure the dropdown list auto-close it when you click outside that auto-complete input :
<divonClick={() => setIsComponentVisible(false)}style={{display: isComponentVisible ? "block" : "none",width: "200vw",height: "200vh",backgroundColor: "transparent",position: "fixed",zIndex: 0,top: 0,left: 0}}/>
  • Finally, add some styling below :

The code for the project is available here on codesandbox,

Well, you’ve got it there. A perfect way to simply integrate auto-complete component .

I hope this has been a fruitful read for you. Please ask any questions in the comments below

Thanks for reading!

This has been developed by myself at eDonec.

--

--