Skip to main content
You are viewing the documentation for InstantSearch.js v4. To upgrade from v3, see the migration guide. Looking for the v3 version of this page? View the v3 docs.

About this widget

connectAutocomplete is a connector. It creates a connected component that provides access to all indices of your InstantSearch instance.
  • To configure the number of hits you show, use either the hitsPerPage or the configure widget.
  • To retrieve results from multiple indices, use the index widget.
The Autocomplete UI library lets you build a full-featured, accessible search experience. For more information, see Integrate Autocomplete with InstantSearch.js.

Customize the UI with connectAutocomplete

If you want to create your own UI of the autocomplete widget, you can use connectors. To use connectAutocomplete, you can import it with the declaration relevant to how you installed InstantSearch.js.
import { connectAutocomplete } from "instantsearch.js/es/connectors";
Then it’s a 3-step process:
JavaScript
// 1. Create a render function
const renderAutocomplete = (renderOptions, isFirstRender) => {
  // Rendering logic
};

// 2. Create the custom widget
const customAutocomplete = connectAutocomplete(renderAutocomplete);

// 3. Instantiate
search.addWidgets([
  customAutocomplete({
    // instance params
  }),
]);

Create a render function

This rendering function is called before the first search (init lifecycle step) and each time results come back from Algolia (render lifecycle step).
JavaScript
const renderAutocomplete = (renderOptions, isFirstRender) => {
  const { indices, currentRefinement, refine, widgetParams } = renderOptions;

  if (isFirstRender) {
    // Do some initial rendering and bind events
  }

  // Render the widget
};

Rendering options

indices
object[]
The indices this widget has access to. You can leverage the highlighting feature of Algolia through the highlight function, directly from the connector’s render function. Each index widget is provided with:
  • indexName: string. The name of the index (can change with sortBy).
  • indexId: string. The identifier of this index object.
  • hits: object[]. The resolved hits from the index matching the query.
  • results: object. The full results object from the Algolia API.
  • sendEvent: function. A function to send click or conversion events. The view event is automatically sent when the connector renders hits. For more information, see the insights middleware.
JavaScript
const renderIndexListItem = ({ indexId, hits }) => `
  <li>
    Index: ${indexId}
    <ol>
      ${hits
        .map(
          (hit, hitIndex) =>
            `<li>
              <p>${instantsearch.highlight({ attribute: "name", hit })}</p>
              <button
                type="button"
                class="btn-add-to-cart"
                data-index-id="${indexId}"
                data-hit-index="${hitIndex}"
              >
                Add to Cart
              </button>
            </li>`,
        )
        .join("")}
    </ol>
  </li>
`;

const renderAutocomplete = (renderOptions, isFirstRender) => {
  const { indices } = renderOptions;
  const container = document.querySelector("#autocomplete");

  if (isFirstRender) {
    container.addEventListener("click", (event) => {
      if (event.target.classList.contains("btn-add-to-cart")) {
        const indexId = event.target.getAttribute("data-index-id");
        const hitIndex = event.target.getAttribute("data-hit-index");
        const index = indices.find((index) => index.indexId === indexId);
        const hit = index.hits[hitIndex];

        index.sendEvent("conversion", hit, "Product Added");
        /*
          A payload like the following is forwarded to the `insights` middleware.
          {
            eventType: 'click',
            insightsMethod: 'clickedObjectIDsAfterSearch',
            payload: {
              eventName: 'Product Added',
              index: '<index-name>',
              objectIDs: ['<object-id>'],
              positions: [<position>],
              queryID: '<query-id>',
            },
            widgetType: 'ais.autocomplete',
          }
        */
      }
    });
  }

  container.innerHTML = `
    <ul>
      ${indices.map(renderIndexListItem).join("")}
    </ul>
  `;
};
currentRefinement
string
The current value of the query.
JavaScript
const renderAutocomplete = (renderOptions, isFirstRender) => {
  const { currentRefinement } = renderOptions;

  document.querySelector("#autocomplete").innerHTML = `
    <input type="search" value="${currentRefinement}">
  `;
};
refine
function
Searches into the indices with the provided query.
JavaScript
const renderIndexListItem = ({ indexId, hits }) => `
  <li>
    Index: ${indexId}
    <ol>
      ${hits
        .map(
          (hit) =>
            `<li>${instantsearch.highlight({ attribute: "name", hit })}</li>`,
        )
        .join("")}
    </ol>
  </li>
`;

const renderAutocomplete = (renderOptions, isFirstRender) => {
  const { indices, currentRefinement, refine } = renderOptions;
  const container = document.querySelector("#autocomplete");

  if (isFirstRender) {
    const input = document.createElement("input");
    const ul = document.createElement("ul");

    input.addEventListener("input", (event) => {
      refine(event.currentTarget.value);
    });

    container.appendChild(input);
    container.appendChild(ul);
  }

  container.querySelector("input").value = currentRefinement;
  container.querySelector("ul").innerHTML = indices
    .map(renderIndexListItem)
    .join("");
};
widgetParams
object
All original widget options forwarded to the render function.
JavaScript
const renderAutocomplete = (renderOptions, isFirstRender) => {
  const { widgetParams } = renderOptions;

  widgetParams.container.innerHTML = "...";
};

// ...

search.addWidgets([
  customAutocomplete({
    container: document.querySelector("#autocomplete"),
  }),
]);

Create and instantiate the custom widget

First, create your custom widgets using a rendering function. Then, instantiate them with parameters. There are two kinds of parameters you can pass:
  • Instance parameters. Predefined options that configure Algolia’s behavior.
  • Custom parameters. Parameters you define to make the widget reusable and adaptable.
Inside the renderFunction, both instance and custom parameters are accessible through connector.widgetParams.
JavaScript
const customAutocomplete = connectAutocomplete(renderAutocomplete);

search.addWidgets([
  customAutocomplete({
    // Optional parameters
    escapeHTML,
  }),
]);

Instance options

escapeHTML
boolean
default:true
Escapes HTML entities from hits string values.
JavaScript
customAutocomplete({
  escapeHTML: false,
});

Full example

<div id="autocomplete"></div>
I