Autocomplete and suggestion in ReactJS


In this article, we will learn how make an autocomplete and suggestion box in React JS. Autocomplete is one of the basic features that every website has, however implementing it in a React website is very complex and problematic. Here, we will see an easy implementation of autocomplete in React JS.

First create a React project −

npx create-react-app tutorialpurpose

Now go to the project directory −

cd tutorialpurpose

Example

First download a package −

npm install --save downshift

This library is used to add suggestion list for searchbox and the list will be written inside an array.

You just copy the following code and change its style and array data. If the structure of your array contains any other key (here, I have “value” as a key), then you just need to change the name of key under <ul> tag.

Add the following lines of code in App.js

import * as React from "react";
import Downshift from "downshift";
const items = [
   { value: "apple" },
   { value: "pear" },
   { value: "orange" },
   { value: "grape" },
   { value: "banana" },
];

export default function App() {
   return (
      <Downshift
         onChange={(selection) =>
           alert(
             selection ? `You selected ${selection.value}` : "Selection Cleared"
            )
         }
         itemToString={(item) => (item ? item.value : "")}>
      {({
         getInputProps,
         getItemProps,
         getLabelProps,
         getMenuProps,
         isOpen,
         inputValue,
         highlightedIndex,
         selectedItem,
         getRootProps,
   }) => (
      <div>
      <label {...getLabelProps()}>Enter a fruit</label>
      <div
         style={{ display: "inline-block" }}
         {...getRootProps({}, { suppressRefError: true })}
         >
         <input {...getInputProps()} />
         </div>
         <ul {...getMenuProps()}>
            {isOpen
               ? items
                  .filter(
                   (item) => !inputValue || item.value.includes(inputValue)).map((item,  index)=> (
               <li
               {...getItemProps({
               key: item.value,
               index,
               item,
               style: {
               backgroundColor:
               highlightedIndex === index ? "lightgray" : "white",fontWeight: selectedItem === item ?"bold" : "normal",},})}>{item.value}</li>)): null}
               </ul>
             </div>
         )}
      </Downshift>
   );
}

Explanation

  • First we created an array of fruits. In return, we created a Downshift component, inside which we defined that on selecting any option, an alert will pop up. We changed all items to string in itemToString attribute.

  • Then between <Downshift> and </Downshift> we mapped through downshift default settings.

  • On mapping, we defined default LabelProps, default rootDiv prop, and in <ul>, we defined the default menu props. menu props is a list from which we are going to suggest.

  • In <ul> we simply filtered on the basis of our input from the search input box and then mapped through it.

  • In <li> we added some default props for reference for suggestion and auto-completion, and style too. You can tweak the style but don’t tweak other things until you know what you are doing.

Output

It will produce the following output −

Updated on: 28-Sep-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements