API Reference / InstantSearch.js Widgets / autocomplete
Aug. 23, 2019

autocomplete

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 renders results from Algolia.

To configure the number of hits you show, use the hitsPerPage widget or the configure widget. To retrieve results from multiple indices, use the index widget.

Alternatively, we provide a library called autocomplete.js that gives you an out-of-the-box autocomplete component ready to use.

Customize the UI - connectAutocomplete

If you want to create your own UI of the autocomplete widget, you can use connectors.

It’s a 3-step process:

// 1. Create a render function
const renderAutocomplete = (renderOptions, isFirstRender) => {
  // Rendering logic
};

// 2. Create the custom widget
const customAutocomplete = instantsearch.connectors.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

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 } = renderOptions;

  document.querySelector('#autocomplete').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 = instantsearch.connectors.connectAutocomplete(
  renderAutocomplete
);

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

Instance options

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
// Helper for the render function
const renderIndexListItem = ({ indexId, hits }) => `
  <li>
    Index: ${indexId}
    <ol>
      ${hits
        .map(
          hit =>
            `<li>${instantsearch.highlight({ attribute: 'name', hit })}</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);
  }

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

// Create the custom widget
const customAutocomplete = instantsearch.connectors.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?