Skip to main content

autocomplete-text

Here's a simple implementation of an Autocomplete Text Input in React with TypeScript:

import React, { useState } from 'react';

type AutocompleteProps = {
suggestions: string[];
};

const AutocompleteInput: React.FC<AutocompleteProps> = ({ suggestions }) => {
const [activeSuggestion, setActiveSuggestion] = useState<number>(0);
const [filteredSuggestions, setFilteredSuggestions] = useState<string[]>([]);
const [showSuggestions, setShowSuggestions] = useState<boolean>(false);
const [input, setInput] = useState<string>('');

const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const userInput = e.currentTarget.value;

// Filter our suggestions that don't contain the user's input
const unLinked = suggestions.filter(
(suggestion) =>
suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
);

setInput(e.currentTarget.value);
setFilteredSuggestions(unLinked);
setActiveSuggestion(0);
setShowSuggestions(true);
};

const onClick = (e: React.MouseEvent<HTMLLIElement, MouseEvent>) => {
setFilteredSuggestions([]);
setInput(e.currentTarget.innerText);
setActiveSuggestion(0);
setShowSuggestions(false);
};

const SuggestionsListComponent = () => {
return filteredSuggestions.length ? (
<ul>
{filteredSuggestions.map((suggestion, index) => {
let className;

// Flag the active suggestion with a class
if (index === activeSuggestion) {
className = "suggestion-active";
}

return (
<li className={className} key={suggestion} onClick={onClick}>
{suggestion}
</li>
);
})}
</ul>
) : (
<div>
<em>No suggestions available.</em>
</div>
);
};

return (
<>
<input
type="text"
onChange={onChange}
value={input}
/>
{showSuggestions && input && <SuggestionsListComponent />}
</>
);
};

export default AutocompleteInput;

To use this AutocompleteInput component, you would pass in an array of suggestions like so:

const App: React.FC = () => {
const suggestions = [
"React",
"Redux",
"React Router",
"Recoil",
"React Query",
"TypeScript"
];

return <AutocompleteInput suggestions={suggestions} />;
};

export default App;

Now, let me know if you'd like me to continue with a step-by-step explanation of how this component works.

Here's a step-by-step explanation of how the Autocomplete Text Input component is implemented:

  1. Define Component Props:

    • Define a TypeScript interface AutocompleteProps that specifies the expected props for the component, which in this case is an array of suggestions.
  2. Component State:

    • Use the useState hook to establish several state variables:
      • activeSuggestion to keep track of the currently highlighted suggestion in the list.
      • filteredSuggestions to maintain a subset of suggestions that match the user input.
      • showSuggestions to control the visibility of the suggestions list.
      • input to store the current value of the input field.
  3. Handle Input Changes:

    • Implement an onChange function that updates the input state as the user types.
    • In the same function, filter the suggestions prop to find items that include the text the user has typed. Set these to filteredSuggestions.
    • Reset activeSuggestion and set showSuggestions to true to show the filtered suggestions.
  4. Handle Click on Suggestion:

    • Create an onClick function that updates the input state to the value of the suggestion that was clicked.
    • Clear the filteredSuggestions, reset activeSuggestion, and hide the suggestions list.
  5. Render Suggestions:

    • Define a SuggestionsListComponent, a functional component that returns either a list of suggestions or a message indicating that no suggestions are available.
    • If there are filteredSuggestions, map through them and create a list item (<li>) for each one. Add a click event handler to each item that calls the onClick function.
    • Highlight the active suggestion by applying a class name conditionally.
  6. Render the Input and Suggestions List:

    • Render an <input> element with props to bind the onChange handler and the input state for its value.
    • Conditionally render the SuggestionsListComponent below the input based on whether showSuggestions is true and if there is input present.
  7. Styling (not included in the code above):

    • You would typically add CSS for .suggestion-active to highlight the active suggestion. This might include a different background color or other visual cues.
  8. Usage:

    • The AutocompleteInput component can be used anywhere by providing it with an array of suggestions. When rendered, it will suggest completions as the user types.

This component is quite basic and could be enhanced with additional features such as keyboard navigation (using the arrow keys to navigate the suggestions) and more complex state management for asynchronous suggestions (e.g., suggestions fetched from an API).