React Reusable Autocomplete Component Tutorial

React reusable autocomplete component tutorial; This extensive guide will help you ascertain the easy way to build autocomplete component in React application using the popular react-autocomplete package.

Autocomplete is also known as word completion. This feature extends the user experience by immaculately predicting the rest of a word a user types in the autocomplete input box. You have probably seen this profound functionality in modern iOS and Android smartphones.

You may also call it predictive text; seldom you press the tab key or the down arrow key to accept a suggestion offered by autocomplete suggestions.

Adding autocomplete in React is easy; in this guide, you will install the react-autocomplete package using the node package manager. React autocomplete is an accessible, extensible autocomplete for React.js. It offers a handy API for implementing autocomplete features in React environment.

React Autocomplete Component Example

  • Step 1: Install New React Project
  • Step 2: Add react-autocomplete Package
  • Step 3: Adding Test Data
  • Step 4: Build React Autocomplete Component
  • Step 5: Desing Autocomplete Component
  • Step 6: Start React Server

Install New React Project

Invoke npx create react app command to install the new version of React app.

npx create-react-app react-autocomplete-demo

Get inside the app directory.

cd react-autocomplete-demo

Add react-autocomplete Package

In this section, you need to open the terminal and type the following command and execute the command to begin installing the react-autocomplete package.

npm install react-autocomplete

Adding Test Data

This section instructs creating the data that we will display in the autocomplete module; you may skip it if you are getting the data dynamically.

You need to get inside the src directory; likewise, create the new file name it test_data.js, furthermore place the following code inside the src/test_data.js file.

export function FruitsCollection() {
    return [
        {
            "name": "apple"
        },
        {
            "name": "apricot"
        },
        {
            "name": "avocado"
        },
        {
            "name": "banana"
        },
        {
            "name": "bell pepper"
        },
        {
            "name": "bilberry"
        },
        {
            "name": "blackberry"
        },
        {
            "name": "blackcurrant"
        },
        {
            "name": "blood orange"
        },
        {
            "name": "blueberry"
        },
        {
            "name": "boysenberry"
        },
        {
            "name": "breadfruit"
        },
        {
            "name": "canary melon"
        },
        {
            "name": "cantaloupe"
        },
        {
            "name": "cherimoya"
        },
        {
            "name": "cherry"
        },
        {
            "name": "chili pepper"
        },
        {
            "name": "clementine"
        },
        {
            "name": "cloudberry"
        },
        {
            "name": "coconut"
        },
        {
            "name": "cranberry"
        },
        {
            "name": "cucumber"
        },
        {
            "name": "currant"
        },
        {
            "name": "damson"
        },
        {
            "name": "date"
        },
        {
            "name": "dragonfruit"
        },
        {
            "name": "durian"
        },
        {
            "name": "eggplant"
        },
        {
            "name": "elderberry"
        },
        {
            "name": "feijoa"
        },
        {
            "name": "fig"
        },
        {
            "name": "goji berry"
        },
        {
            "name": "gooseberry"
        },
        {
            "name": "grape"
        },
        {
            "name": "grapefruit"
        },
        {
            "name": "guava"
        },
        {
            "name": "honeydew"
        },
        {
            "name": "huckleberry"
        },
        {
            "name": "jackfruit"
        },
        {
            "name": "jambul"
        },
        {
            "name": "jujube"
        },
        {
            "name": "kiwi fruit"
        },
        {
            "name": "kumquat"
        },
        {
            "name": "lemon"
        },
        {
            "name": "lime"
        },
        {
            "name": "loquat"
        },
        {
            "name": "lychee"
        },
        {
            "name": "mandarine"
        },
        {
            "name": "mango"
        },
        {
            "name": "mulberry"
        },
        {
            "name": "nectarine"
        },
        {
            "name": "nut"
        },
        {
            "name": "olive"
        },
        {
            "name": "orange"
        },
        {
            "name": "pamelo"
        },
        {
            "name": "papaya"
        },
        {
            "name": "passionfruit"
        },
        {
            "name": "peach"
        },
        {
            "name": "pear"
        },
        {
            "name": "persimmon"
        },
        {
            "name": "physalis"
        },
        {
            "name": "pineapple"
        },
        {
            "name": "plum"
        },
        {
            "name": "pomegranate"
        },
        {
            "name": "pomelo"
        },
        {
            "name": "purple mangosteen"
        },
        {
            "name": "quince"
        },
        {
            "name": "raisin"
        },
        {
            "name": "rambutan"
        },
        {
            "name": "raspberry"
        },
        {
            "name": "redcurrant"
        },
        {
            "name": "rock melon"
        },
        {
            "name": "salal berry"
        },
        {
            "name": "satsuma"
        },
        {
            "name": "star fruit"
        },
        {
            "name": "strawberry"
        },
        {
            "name": "tamarillo"
        },
        {
            "name": "tangerine"
        },
        {
            "name": "tomato"
        },
        {
            "name": "ugli fruit"
        },
        {
            "name": "watermelo"
        }
    ]
}

export function getFruitName(state, value) {
    return (
        state.name.toLowerCase().indexOf(value.toLowerCase()) !== -1
    );
}

Build React Autocomplete Component

In this section, we will use the Autocomplete directive and its handy APIs to render Fruits data and display it into the autocomplete component, and you need to open and update the src/App.js file.

import React, { Component } from 'react';

import Autocomplete from 'react-autocomplete';
import './App.css';
import { FruitsCollection, getFruitName } from './test_data';

class App extends Component {

  state = { 
    value: '' 
  };

  render() {
    return (
      <div className="instant-search">
        
        <h2>React Autocomplete Component</h2>

        <Autocomplete
          value={this.state.value}
          items={FruitsCollection()}
          getItemValue={res => res.name}
          shouldItemRender={getFruitName}
          renderMenu={res => (
            <div className="dropdown" key="{res}">
              {res}
            </div>
          )}
          renderItem={(res, isHighlighted) =>
            <div className={`item ${isHighlighted ? 'active' : ''}`}>
              {res.name}
            </div>
          }
          onChange={(e, value) => this.setState({ value })}
          onSelect={value => this.setState({ value })}
        />
      </div>
    );
  }
}

export default App;

Design Autocomplete Component

Lastly, we need to add spruce up the live search component by adding the little bit of CSS styling, and you have to add the following code into the src/index.css file.

body {
  margin: 60px 0 0;
  text-align: center;
  background-color: #edf0f4;
  font-family: sans-serif;
}

.instant-search {
  width: 400px;
  position: relative;
  display: inline-block;
}

.instant-search input {
  border: 1px solid #cecece;
  padding: 15px 20px;
  font-size: 14px;
  width: 100%;
}

.instant-search input:focus {
  border-color: #ff00aa;
  box-shadow: none;
  outline: none;
}

.instant-search .dropdown {
  padding: 0;
  text-align: left;
  max-height: 300px;
  overflow: hidden;
  overflow-y: auto;
  border-top: none;
  background-color: #ffebf8;
  border: 1px solid #ff00aa;  
}

.instant-search .item  {
  display: block;
  cursor: pointer;
  font-size: 15px;
  padding: 15px;
}

.instant-search .item.active {
  background-color: #ff00aa;
  color: #ffebf8;
}

.instant-search .item:hover {
  background-color: #ff00aa;
  color: #ffebf8;
}

.instant-search > div {
  width: 100%;
}

Start React Server

Eventually, we have reached the last section of this guide; you need to evoke the npm start command to start the react development server.

npm start

After initializing the above command following url manifest on the terminal, you may use it in the browser to run the app.

http://localhost:3000

React Autocomplete Component

Conclusion

We have gone through every step essential for building react autocomplete functional component; this was just the basic predictive search; however, you may go ahead and build more extensive features using the react-autocomplete plugin.