useRef
and
useEffect
Hooks to create and mount the component.
It doesn’t define specific sources.
Rather, you can pass sources and other
options as
props.
Before you begin
The guide assumes you’re familiar with the basic Autocomplete configuration options and have an existing React (v16.8+) app to which you want to add an Autocomplete menu.Create the component
Add the following starter code for creating a React component. This component uses theuseRef
Hook to create a mutable ref object,
containerRef
, for mounting the autocomplete.
All that you need to render is a div
with the containerRef
as the ref
.
JSX
Attach the autocomplete menu to the DOM
Now that you have access to the DOM through thecontainerRef
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.
The following examples specify where to mount your Autocomplete component with the container
option,
but lets all other options
get configured through props.
The default Autocomplete implementation uses Preact APIs to create and render elements,
so you need to replace them with React APIs to properly render the views.
Depending on your React version, the implementation slightly differs.
In both cases, clean up the effect by returning a function that destroys the Autocomplete instance.
With React 18
With React 18, you should only pass ReactcreateElement
and Fragment
to the renderer
option.
To silence the warning from Autocomplete, you can pass an empty function to renderer.render
.
Instead, you should use the render
option to create a Root
object with the React createRoot
function, then use this object to render.
JSX
With React 16.8 or 17
With React 16.8 or 17, you need to importcreateElement
, Fragment
, and render
from React and provide them to the Autocomplete renderer
option.
JSX
Use the component
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 about using Algolia as a source, see Getting started.
JSX
Create templates
The example preceding passes<ProductItem />
, another React component,
for the item
template.
JSX
Further UI customization
If you want to build a custom UI that differs from theautocomplete-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 frontend framework.