Learn how to create and use a React Autocomplete component.
This guide shows how to create a React Autocomplete component. It uses the
useEffect hooks to create and mount the component. It doesn't define specific sources. Rather, you can pass sources and other options as props.
This tutorial assumes that you have:
- an existing React (v16.8+) application where you want to implement the autocomplete menu
- familiarity with the basic Autocomplete configuration options
Start with some boilerplate for creating a React component. This component uses the
useRef hook to create a mutable ref object,
containerRef, to mount the autocomplete on. To learn more about this hook, check out the
useRef React documentation.
All that you need to render is a
div with the
containerRef as the
Now that you have access to the DOM through the
containerRef object, you can create and mount the Autocomplete instance. Upon instantiation, you can include any desired Autocomplete options and rely on
props to pass any options you want to remain configurable.
You must also pass the
render parameters. This is because the default Autocomplete implementation uses Preact's version of
render. Without providing React's version of these, the Autocomplete instance won't render the views properly.
Don't forget to clean up the effect by returning a function that destroys the Autocomplete instance.
Now that you've created an
<Autocomplete /> component, you can use it in your React application.
The usage below sets
openOnFocus and sources through props. This example uses an Algolia index as a source, but you could use anything else you want, including plugins. For more information on using Algolia as a source, check out the Getting Started guide.
The example above passes
<ProductItem />, another React component, for the
item template. When creating templates, there's one thing to keep in mind. If you're using the highlighting and snippeting utilities, you must pass them React's
createElement function. Without doing this, the utilities default to
preact.createElement and won't work properly.
The highlighting and snippeting utilities are:
Here's an example using
If you want to build a custom UI that differs from the
autocomplete-js output, check out the guide on creating a custom renderer. This guide outlines how to create a custom React renderer specifically, but the underlying principles are the same for any other front-end framework.