React Autocomplete: The Complete Guide

1
2002
How to create Autocomplete Component in React

In modern web development, improving the user experience with React is easy. The concept of autocomplete is straightforward. It is a list of suggestions based on a user’s input. A user can then hit enter to complete the word or phrase. It saves the user time, which tends to make users very happy.

React Autocomplete

To create an autocomplete component in React, use the react-autocomplete library. The react-autocomplete module provides properties, methods, and events that can trigger an ajax request on typing, which will fetch the list items and render them inside the render menu.

Autocomplete in React can be implemented in how the suggestions are filtered and presented to the user.

In this article, we will use a fixed list of recommendations passed to our component. Then, as the user types, we will filter the results and only show the suggestions that contain the user’s input anywhere in the suggestion.

But first, let us install React.js using the following command.

Step 1: Install React.js.

Type the following command.

npx create-react-app my-app
cd my-app
npm start

React Autocomplete Example Tutorial

Now, install the react-autocomplete library using the following command.

npm install --save react-autocomplete

Step 2: Create the static data.

Inside the src folder, create one file called data.js and add the following function that returns the static data.

// data.js

export function getStocks() {
  return [
    { abbr: 'ADANIPORTS', name: 'Adani Ports & Special Economic Zone Ltd.' },
    { abbr: 'ASIANPAINT', name: 'Asian Paints Ltd.' },
    { abbr: 'AXISBANK', name: 'Axis Bank Ltd.' },
    { abbr: 'BAJAJ-AUTO', name: 'Bajaj Auto Ltd.' },
    { abbr: 'BAJFINANCE', name: 'Bajaj Finance' },
    { abbr: 'BAJAJFINSV', name: 'Bajaj Finserv Ltd.' },
    { abbr: 'BPCL', name: 'Bharat Petroleum Corporation Ltd.' },
    { abbr: 'BHARTIARTL', name: 'Bharti Airtel Ltd.' },
    { abbr: 'INFRATEL', name: 'Bharti Infratel' },
    { abbr: 'CIPLA', name: 'Cipla Ltd.' },
    { abbr: 'COALINDIA', name: 'Coal India Ltd' },
    { abbr: 'DRREDDY', name: 'Dr. Reddys Laboratories Ltd.' },
    { abbr: 'EICHERMOT', name: 'Eicher Motors Ltd.' },
    { abbr: 'GAIL', name: 'GAIL (India) Ltd.' },
    { abbr: 'GRASIM', name: 'Grasim Industries Ltd.' },
    { abbr: 'HCLTECH', name: 'HCL Technologies Ltd.' },
    { abbr: 'HDFCBANK', name: 'HDFC Bank Ltd.' },
    { abbr: 'HEROMOTOCO', name: 'Hero MotoCorp Ltd.' },
    { abbr: 'HINDALCO', name: 'Hindalco Industries Ltd.' },
    { abbr: 'HINDPETRO', name: 'Hindustan Petroleum Corporation Ltd.' },
    { abbr: 'HINDUNILVR', name: 'Hindustan Unilever Ltd.' },
    { abbr: 'HDFC', name: 'Housing Development Finance Corporation Ltd.' },
    { abbr: 'ITC', name: 'I T C Ltd.' },
    { abbr: 'ICICIBANK', name: 'ICICI Bank Ltd.' },
    { abbr: 'IBULHSGFIN', name: 'Indiabulls Housing Finance' },
    { abbr: 'IOC', name: 'Indian Oil Corporation Ltd.' },
    { abbr: 'INDUSINDBK', name: 'IndusInd Bank Ltd.' },
    { abbr: 'INFY	', name: 'Infosys Ltd.' },
    { abbr: 'KOTAKBANK', name: 'Kotak Mahindra Bank Ltd.' },
    { abbr: 'LT', name: 'Larsen & Toubro Ltd.' },
    { abbr: 'LUPIN', name: 'Lupin Ltd.' },
    { abbr: 'M&M', name: 'Mahindra & Mahindra Ltd.' },
    { abbr: 'MARUTI', name: 'Maruti Suzuki India Ltd.' },
    { abbr: 'NTPC', name: 'NTPC Ltd.' },
    { abbr: 'ONGC', name: 'Oil & Natural Gas Corporation Ltd.' },
    { abbr: 'POWERGRID', name: 'Power Grid Corporation of India Ltd.' },
    { abbr: 'RELIANCE', name: 'Reliance Industries Ltd.' },
    { abbr: 'SBIN', name: 'State Bank of India' },
    { abbr: 'SUNPHARMA', name: 'Sun Pharmaceutical Industries Ltd.' },
    { abbr: 'TCS', name: 'Tata Consultancy Services Ltd.' },
    { abbr: 'TATAMOTORS', name: 'Tata Motors Ltd.' },
    { abbr: 'TATASTEEL', name: 'Tata Steel Ltd.' },
    { abbr: 'TECHM', name: 'Tech Mahindra Ltd.' },
    { abbr: 'TITAN', name: 'Titan Company Ltd.' },
    { abbr: 'ULTRACEMCO', name: 'UltraTech Cement Ltd.' },
    { abbr: 'UPL', name: 'UPL Ltd.' },
    { abbr: 'VEDL', name: 'Vedanta Ltd' },
    { abbr: 'WIPRO', name: 'Wipro Ltd.' },
    { abbr: 'YESBANK', name: 'Yes Bank Ltd.' },
    { abbr: 'ZEEL', name: 'Zee Entertainment Enterprises Ltd.' }
  ];
}

This function will return the top 50 stocks’ name and their abbreviation of Indian Share Market.

Also, we need to create one more function here, and that is matchStocks.

This function allows us to filter out the stocks that the user in the input area types. So when the user starts typing in the text box, it will compare to the array of stocks, and if find the match then return and display it to the user.

So write the second function and export it from the data.js file.

// data.js

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

So, we essentially import these functions inside the App.js file and pass it to the Autocomplete component.

Step 3: Autocomplete API

It has the following properties.

value: It is the default value of the textbox. In our case, it will be empty or “.

inputProps: It is an object. Props passed to props.renderInput; By default, these props will be applied to the <input /> element rendered by Autocomplete unless you have specified a custom value for props.renderInput
wrapperStyle: It is an object, and it has the following default value.
{
display: 'inline-block'
}
items: It is an array of data defined in the data.js file. In our case, it is stock market data.
getItemValue: Used to read the display value from each entry in items.
shouldItemRender: It is a function. Invoked for each entry in items and its return value is used to determine whether or not it should be displayed in the drop-down menu. By de, fault all items are always rendered.
onChange: It is a function invoked every time the user changes the input’s value.
onSelect: This function invokes when the user selects an item from the drop-down menu.
renderMenu: The function invoked to generate the render tree for the drop-down menu. Ensure the returned tree includes every item entry, or else the highlighted order and keyboard navigation logic will break. In addition, the styles will contain { top, left, minWidth } which are the coordinates of the top-left corner and the width of the drop-down menu.
renderItem: The function invoked for each entry in the items also passes shouldItemRender to generate the render tree for each item in the drop-down menu. The style is an optional set of styles that can be applied to improve the look/feel of the items in the drop-down menu.

Step 4: Add Autocomplete component into App.js file.

So our final App.js file looks like this.

import React, { Component } from 'react';
import Autocomplete from  'react-autocomplete';
import { getStocks, matchStocks } from './data';
import './App.css';

class App extends Component {

  state = { value: '' };

  render() {
    return (
      <div style = {{ marginTop: 40, marginLeft: 50 }}>
        <Autocomplete
          value={ this.state.value }
          inputProps={{ id: 'states-autocomplete' }}
          wrapperStyle={{ position: 'relative', display: 'inline-block' }}
          items={ getStocks() }
          getItemValue={ item => item.name }
          shouldItemRender={ matchStocks }
          onChange={(event, value) => this.setState({ value }) }
          onSelect={ value => this.setState({ value }) }
          renderMenu={ children => (
            <div className = "menu">
              { children }
            </div>
          )}
          renderItem={ (item, isHighlighted) => (
            <div
              className={`item ${isHighlighted ? 'item-highlighted' : ''}`}
              key={ item.abbr } >
              { item.name }
            </div>
          )}
        />
      </div>
      );
    }
  }

export default App;

Here, we have used all the properties that we have discussed earlier. Some are still not there, but you can check them out on Github.

And our data.js file looks like this.

// data.js

export function getStocks() {
  return [
    { abbr: 'ADANIPORTS', name: 'Adani Ports & Special Economic Zone Ltd.' },
    { abbr: 'ASIANPAINT', name: 'Asian Paints Ltd.' },
    { abbr: 'AXISBANK', name: 'Axis Bank Ltd.' },
    { abbr: 'BAJAJ-AUTO', name: 'Bajaj Auto Ltd.' },
    { abbr: 'BAJFINANCE', name: 'Bajaj Finance' },
    { abbr: 'BAJAJFINSV', name: 'Bajaj Finserv Ltd.' },
    { abbr: 'BPCL', name: 'Bharat Petroleum Corporation Ltd.' },
    { abbr: 'BHARTIARTL', name: 'Bharti Airtel Ltd.' },
    { abbr: 'INFRATEL', name: 'Bharti Infratel' },
    { abbr: 'CIPLA', name: 'Cipla Ltd.' },
    { abbr: 'COALINDIA', name: 'Coal India Ltd' },
    { abbr: 'DRREDDY', name: 'Dr. Reddys Laboratories Ltd.' },
    { abbr: 'EICHERMOT', name: 'Eicher Motors Ltd.' },
    { abbr: 'GAIL	', name: 'GAIL (India) Ltd.' },
    { abbr: 'GRASIM', name: 'Grasim Industries Ltd.' },
    { abbr: 'HCLTECH', name: 'HCL Technologies Ltd.' },
    { abbr: 'HDFCBANK', name: 'HDFC Bank Ltd.' },
    { abbr: 'HEROMOTOCO', name: 'Hero MotoCorp Ltd.' },
    { abbr: 'HINDALCO', name: 'Hindalco Industries Ltd.' },
    { abbr: 'HINDPETRO', name: 'Hindustan Petroleum Corporation Ltd.' },
    { abbr: 'HINDUNILVR', name: 'Hindustan Unilever Ltd.' },
    { abbr: 'HDFC', name: 'Housing Development Finance Corporation Ltd.' },
    { abbr: 'ITC', name: 'I T C Ltd.' },
    { abbr: 'ICICIBANK', name: 'ICICI Bank Ltd.' },
    { abbr: 'IBULHSGFIN', name: 'Indiabulls Housing Finance' },
    { abbr: 'IOC', name: 'Indian Oil Corporation Ltd.' },
    { abbr: 'INDUSINDBK', name: 'IndusInd Bank Ltd.' },
    { abbr: 'INFY	', name: 'Infosys Ltd.' },
    { abbr: 'KOTAKBANK', name: 'Kotak Mahindra Bank Ltd.' },
    { abbr: 'LT', name: 'Larsen & Toubro Ltd.' },
    { abbr: 'LUPIN', name: 'Lupin Ltd.' },
    { abbr: 'M&M', name: 'Mahindra & Mahindra Ltd.' },
    { abbr: 'MARUTI', name: 'Maruti Suzuki India Ltd.' },
    { abbr: 'NTPC', name: 'NTPC Ltd.' },
    { abbr: 'ONGC', name: 'Oil & Natural Gas Corporation Ltd.' },
    { abbr: 'POWERGRID', name: 'Power Grid Corporation of India Ltd.' },
    { abbr: 'RELIANCE', name: 'Reliance Industries Ltd.' },
    { abbr: 'SBIN', name: 'State Bank of India' },
    { abbr: 'SUNPHARMA', name: 'Sun Pharmaceutical Industries Ltd.' },
    { abbr: 'TCS', name: 'Tata Consultancy Services Ltd.' },
    { abbr: 'TATAMOTORS', name: 'Tata Motors Ltd.' },
    { abbr: 'TATASTEEL', name: 'Tata Steel Ltd.' },
    { abbr: 'TECHM', name: 'Tech Mahindra Ltd.' },
    { abbr: 'TITAN', name: 'Titan Company Ltd.' },
    { abbr: 'ULTRACEMCO', name: 'UltraTech Cement Ltd.' },
    { abbr: 'UPL', name: 'UPL Ltd.' },
    { abbr: 'VEDL', name: 'Vedanta Ltd' },
    { abbr: 'WIPRO', name: 'Wipro Ltd.' },
    { abbr: 'YESBANK', name: 'Yes Bank Ltd.' },
    { abbr: 'ZEEL', name: 'Zee Entertainment Enterprises Ltd.' }
  ];
}

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

Finally, the App.css file looks like this.

body {
  color: #333;
  font-family: "Helvetica Neue", Arial, sans-serif;
  font-weight: 200;
}

.example {
  padding: 0 25px;
}

label {
  display: block;
  margin: 5px 0;
}

code {
  padding: .2em .5em;
  font-size: 85%;
  background-color: rgba(0,0,0,0.04);
  border-radius: 3px;
}

.menu {
  position: absolute;
  box-sizing: border-box;
  width: 100%;
  border: 1px solid #cccccc;
}

.item {
  padding: 2px 6px;
  cursor: default;
}

.item-highlighted {
  color: white;
  background-color: #4095bf;
}

.item-header {
  background-color: #eeeeee;
  color: #454545;
  font-weight: bold;
}

Save all the files and go to the http://localhost:3000/

Type the stocks from the array of data, and you will get the suggestions.

React Autocomplete Tutorial

That’s it for this tutorialThanks for taking it.

1 Comment

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.