🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
UI libraries / InstantSearch.js / Widgets

About this widget

You are currently reading the documentation for InstantSearch.js V4. Read our migration guide to learn how to upgrade from V3 to V4. You can still access the V3 documentation for this page.

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 library lets you build a full-featured, accessible search experience.

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.

1
import { connectAutocomplete } from 'instantsearch.js/es/connectors';

Then it’s a 3-step process:

// 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).

const renderAutocomplete = (renderOptions, isFirstRender) => {
  const {
    object[] indices,
    string currentRefinement,
    function refine,
    object widgetParams,
  } = renderOptions;

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

  // Render the widget
}

Rendering options

Parameter Description
indices
type: 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, please check the insights middleware reference.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
type: string

The current value of the query.

1
2
3
4
5
6
7
const renderAutocomplete = (renderOptions, isFirstRender) => {
  const { currentRefinement } = renderOptions;

  document.querySelector('#autocomplete').innerHTML = `
    <input type="search" value="${currentRefinement}" />
  `;
};
refine
type: function

Searches into the indices with the provided query.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
type: object

All original widget options forwarded to the render function.

1
2
3
4
5
6
7
8
9
10
11
12
13
const renderAutocomplete = (renderOptions, isFirstRender) => {
  const { widgetParams } = renderOptions;

  widgetParams.container.innerHTML = '...';
};

// ...

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

Create and instantiate the custom widget

We first create custom widgets from our rendering function, then we instantiate them. When doing that, there are two types of parameters you can give:

  • Instance parameters: they are predefined parameters that you can use to configure the behavior of Algolia.
  • Your own parameters: to make the custom widget generic.

Both instance and custom parameters are available in connector.widgetParams, inside the renderFunction.

const customAutocomplete = connectAutocomplete(
  renderAutocomplete
);

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

Instance options

Parameter Description
escapeHTML
type: boolean
default: true
Optional

Escapes HTML entities from hits string values.

1
2
3
customAutocomplete({
  escapeHTML: false,
});

Full example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Helper for the render function
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>
`;

// Create the render function
const renderAutocomplete = (renderOptions, isFirstRender) => {
  const { indices, currentRefinement, refine, widgetParams } = renderOptions;

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

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

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

    ul.addEventListener('click', (event) => {
      if (event.target.className === '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');
      }
    });
  }

  widgetParams.container.querySelector('input').value = currentRefinement;
  widgetParams.container.querySelector('ul').innerHTML = indices
    .map(renderIndexListItem)
    .join('');
};

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

// Instantiate the custom widget
search.addWidgets([
  index({ indexName: 'instant_search_price_asc' }),
  index({ indexName: 'instant_search_price_desc' }),

  customAutocomplete({
    container: document.querySelector('#autocomplete'),
  })
]);
Did you find this page helpful?