React Autocomplete component using React Hooks
Autocomplete or word completion works so that when the writer writes the first letter or letters of a word, the program predicts one or more possible words as choices. If the word he intends to write is included in the list he can select it.
What will follow is my attempt to build an autocomplete component only using React and custom React hooks.
We would like our autocomplete to do the following:
- Style Input and Option List
- Static source
- Remote source
- Scrollable results
- Keyboard navigation
- Jump to the first option
- Jump to the last option
- Select option on “Enter” or mouse click
Let’s create the UI component
As can be seen, all the styling and layout is done here. The functionality of the input, options list (ul), and options (li) is delegated to the custom hook through the objects bindInput, bindOptions, and bindOption
Lastly, the autocomplete component will be able to work with a remote source simply by changing the source and optionally setting a delay so that the remote source is only called after keyboard typing delay: