Code Playground.

How to Build an Autocomplete Component in React

CFG

How to Build an Autocomplete Component in React

Autocomplete is an element that recommends words or expressions that total a client's underlying information. In this article, we'll assemble an autocomplete part without any preparation in React.

Build an autocomplete component from scratch in React that suggests words and phrases to complete a user's input.

Getting started

npx create-react-app autocomplete-app
cd autocomplete-app && yarn start 

Building a React autocomplete component

import { useState } from "react";

const AutoComplete = ({ suggestions }) => {
   return (
    <>
      <input
        type="text"
      />
    </>
  );
};
export default AutoComplete;

Defining methods

const [filteredSuggestions, setFilteredSuggestions] = useState([]);
  const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(0);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [input, setInput] = useState("");
const onChange = (e) => {
    const userInput = e.target.value;
    const unLinked = suggestions.filter(
      (suggestion) =>
        suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
    );

    setInput(e.target.value);
    setFilteredSuggestions(unLinked);
    setActiveSuggestionIndex(0);
    setShowSuggestions(true);
  };

Adding a suggestion

const onClick = (e) => {
    setFilteredSuggestions([]);
    setInput(e.target.innerText);
    setActiveSuggestionIndex(0);
    setShowSuggestions(false);
  };

Create a SuggestionsListComponent

const SuggestionsListComponent = () => {
    return filteredSuggestions.length ? (
      <ul class="suggestions">
        {filteredSuggestions.map((suggestion, index) => {
          let className;
          // Flag the active suggestion with a class
          if (index === activeSuggestionIndex) {
            className = "suggestion-active";
          }
          return (
            <li className={className} key={suggestion} onClick={onClick}>
              {suggestion}
            </li>
          );
        })}
      </ul>
    ) : (
      <div class="no-suggestions">
        <em>No suggestions, you're on your own!</em>
      </div>
    );
  };

Inputting user text

return (
    <>
      <input
        type="text"
        onChange={onChange}
        onKeyDown={onKeyDown}
        value={input}
      />
      {showSuggestions && input && <SuggestionsListComponent />}
    </>
  );
};
export default AutoComplete;
import React from "react";
import Autocomplete from "./Autocomplete";
import "./styles.css";

const App = () => {
  return (
    <div>
      <h1>React Autocomplete Demo</h1>
      <h2>Start typing and experience React autocomplete!</h2>
      <Autocomplete
        suggestions={[
          "Alligator",
          "Bask",
          "Crocodilian",
          "Death Roll",
          "Eggs",
          "Jaws",
          "Reptile",
          "Solitary",
          "Tail",
          "Wetlands"
        ]}
      />
    </div>
  );
};
body {
  font-family: sans-serif;
}
input {
  border: 1px solid #999;
  padding: 0.5rem;
  width: 300px;
}
.no-suggestions {
  color: #999;
  padding: 0.5rem;
}
.suggestions {
  border: 1px solid #999;
  border-top-width: 0;
  list-style: none;
  margin-top: 0;
  max-height: 143px;
  overflow-y: auto;
  padding-left: 0;
  width: calc(300px + 1rem);
}
.suggestions li {
  padding: 0.5rem;
}
.suggestion-active,
.suggestions li:hover {
  background-color: #008f68;
  color: #fae042;
  cursor: pointer;
  font-weight: 700;
}
.suggestions li:not(:last-of-type) {
  border-bottom: 1px solid #999;
}

In this instructional exercise, we concealed setting a React project, fabricating an autocomplete part, and styling our application.

#react #reactjs #javascript #webdev




CFG