AppDividend
Latest Code Tutorials

React Autocomplete Example Tutorial

2,196

Get real time updates directly on you device, subscribe now.

React Autocomplete Example Tutorial is today’s main topic.  In the modern web development, improving the user experience, and 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 of phrase. It saves the user’s time, and that tends to make users very happy. Autocomplete can be implemented in any number of ways regarding how the suggestions are filtered and presented to the user, and in this article, we are going to use a fixed list of recommendations passed to our component. As the user types, we will filter the results and only show the suggestions that contain the user’s input anywhere in the suggestion.

If you want to learn more about React.js then checkout this  React 16 – The Complete Guide (incl. React Router 4 & Redux) Guide. It has a very brief intro about React and Redux.
React 16 – The Complete Guide (incl. React Router 4 & Redux)

React Autocomplete Example Tutorial

We use the library for this tutorial called react-autocompleteBut first, let us install the React.js using the following command.

#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

#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.' }
  ];
}
Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

This function will return the top 50 stocks name and its 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 are typing by the user in the input area. 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 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, now basically, we import these functions inside App.js file and pass it to the Autocomplete component.

#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 default value of the following.
{
display: 'inline-block'
}
items: It is an array of data, which is defined in the data.js file. In our case, it is a 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 and 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: It is the function and invoked to generate the render tree for the drop-down menu. Ensure the returned tree includes every entry in items or else the highlighted order and keyboard navigation logic will break. 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: It is the function and invoked for each entry in the items that also passes shouldItemRender to generate the render tree for each item in the drop-down menu. The styles is an optional set of styles that can be applied to improve the look/feel of the items in the drop-down menu.

#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 of them are still not there, but you can check it out on the Github.

Related Posts
1 of 20

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, 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

So, finally, we have completed the React Autocomplete Example Tutorial. Thanks for taking.

1 Comment
  1. vikas says

    Hi krunal,

    can you please post an example for multiple select with select all option and check box please.

Leave A Reply

Your email address will not be published.

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