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:
Define Component Props:
- Define a TypeScript interface
AutocompleteProps
that specifies the expected props for the component, which in this case is an array ofsuggestions
.
- Define a TypeScript interface
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.
- Use the
Handle Input Changes:
- Implement an
onChange
function that updates theinput
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 tofilteredSuggestions
. - Reset
activeSuggestion
and setshowSuggestions
to true to show the filtered suggestions.
- Implement an
Handle Click on Suggestion:
- Create an
onClick
function that updates theinput
state to the value of the suggestion that was clicked. - Clear the
filteredSuggestions
, resetactiveSuggestion
, and hide the suggestions list.
- Create an
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 theonClick
function. - Highlight the active suggestion by applying a class name conditionally.
- Define a
Render the Input and Suggestions List:
- Render an
<input>
element with props to bind theonChange
handler and theinput
state for its value. - Conditionally render the
SuggestionsListComponent
below the input based on whethershowSuggestions
is true and if there is input present.
- Render an
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.
- You would typically add CSS for
Usage:
- The
AutocompleteInput
component can be used anywhere by providing it with an array ofsuggestions
. When rendered, it will suggest completions as the user types.
- The
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).