Skip to content

Instantly share code, notes, and snippets.

@jsdevspace
Last active September 9, 2024 07:10
Show Gist options
  • Select an option

  • Save jsdevspace/37634e7690e43e5af7d9862d20563ee7 to your computer and use it in GitHub Desktop.

Select an option

Save jsdevspace/37634e7690e43e5af7d9862d20563ee7 to your computer and use it in GitHub Desktop.
AutoComplete.tsx
import React, { ChangeEvent, useRef, useState } from 'react';
type AutoCompleteProps = {
possibleValues: string[];
handleKeydown: () => void;
setTags: (values: string[]) => void;
};
function Autocomplete({ possibleValues, handleKeydown, setTags }: AutoCompleteProps) {
const inputRef = useRef(null);
const [inputValue, setInputValue] = useState('');
const [suggestions, setSuggestions] = useState<string[]>([]);
const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
const value = event.target.value;
setInputValue(value);
if (value.length > 0) {
const filteredSuggestions = possibleValues.filter((suggestion) =>
suggestion.toLowerCase().includes(value.toLowerCase()),
);
setSuggestions(filteredSuggestions);
} else {
setSuggestions([]);
}
};
const handleSuggestionClick = (value: string) => {
setTags((tags: string[]) => {
if (tags.some((tag) => tag.toLowerCase() === value.toLowerCase())) {
return [...tags];
} else {
return [...tags, value];
}
});
setSuggestions([]);
setInputValue('');
inputRef.current.focus();
};
const onKeyDown = (e: ChangeEvent<HTMLInputElement> & KeyboardEvent) => {
handleKeydown(e);
if (e.key === 'Enter') {
setInputValue('');
setSuggestions([]);
inputRef.current.focus();
}
};
return (
<>
<input
type='text'
value={inputValue}
onChange={handleInputChange}
aria-autocomplete='list'
aria-controls='autocomplete-list'
onKeyDown={onKeyDown}
className='text-input'
autoFocus
ref={inputRef}
/>
<div className='autocomplete-wrapper'>
{suggestions.length > 0 && (
<ul id='autocomplete-list' className='suggestions-list' role='listbox'>
{suggestions.map((suggestion, index) => (
<li key={index} onClick={() => handleSuggestionClick(suggestion)} role='option'>
{suggestion}
</li>
))}
</ul>
)}
</div>
</>
);
}
export default Autocomplete;
@jsdevspace

jsdevspace commented Sep 9, 2024

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment