> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# searchBox

> Lets users perform a search using text input.

export const SearchQuery = () => <Tooltip tip="The text users enter into a search box. In the Search API, this corresponds to the query parameter. A search query is often used with filters, facets, and other parameters, but these aren't part of the query text itself.">
    search query
  </Tooltip>;

<div className="not-prose algolia-flavor-switcher">
  <div className="afs-dropdown">
    <div className="afs-trigger" role="button" tabIndex="0" aria-haspopup="listbox">
      <span className="afs-current">JavaScript</span>

      <svg className="afs-chevron lucide lucide-chevron-down" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="m6 9 6 6 6-6" />
      </svg>
    </div>

    <ul className="afs-menu" role="listbox">
      <li role="option" aria-selected="true"><a className="afs-option is-current" href="/doc/api-reference/widgets/search-box/js"><span className="afs-option-name">JavaScript</span><span className="afs-option-lib">InstantSearch.js</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/search-box/react"><span className="afs-option-name">React</span><span className="afs-option-lib">React InstantSearch</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/search-box/vue"><span className="afs-option-name">Vue</span><span className="afs-option-lib">Vue InstantSearch</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/search-box/ios"><span className="afs-option-name">iOS</span><span className="afs-option-lib">InstantSearch iOS</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/search-box/android"><span className="afs-option-name">Android</span><span className="afs-option-lib">InstantSearch Android</span></a></li>
    </ul>
  </div>
</div>

```ts Signature theme={"system"}
searchBox({
  container: string | HTMLElement,
  // Optional parameters
  placeholder?: string,
  autofocus?: boolean,
  ignoreCompositionEvents?: boolean,
  searchAsYouType?: boolean,
  showReset?: boolean,
  showSubmit?: boolean,
  showLoadingIndicator?: boolean,
  aiMode?: boolean,
  queryHook?: function,
  templates?: object,
  cssClasses?: object,
});
```

## Import

<CodeGroup>
  ```js Package manager theme={"system"}
  import { searchBox } from "instantsearch.js/es/widgets";
  ```

  ```js CDN theme={"system"}
  const { searchBox } = instantsearch.widgets;
  // or directly use instantsearch.widgets.searchBox()
  ```
</CodeGroup>

<Card title="See this widget in action" icon="monitor-play" href="https://instantsearchjs.netlify.app/stories/js/?path=/story/basics-searchbox--default" horizontal>
  Preview this widget and its behavior.
</Card>

## About this widget

The `searchBox` widget is used to let users perform a text-based <SearchQuery />.

This usually is the main entry point to start the search in an InstantSearch context.
It's usually placed at the top of a search experience, so that users can start searching right away.

## Examples

```js JavaScript icon=code theme={"system"}
searchBox({
  container: "#searchbox",
});
```

## Options

<ParamField body="container" type="string | HTMLElement" required>
  The CSS Selector or `HTMLElement` to insert the widget into.

  <CodeGroup>
    ```js string theme={"system"}
    searchBox({
      container: "#searchbox",
    });
    ```

    ```js HTMLElement theme={"system"}
    searchBox({
      container: document.querySelector("#searchbox"),
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="placeholder" type="string">
  The placeholder text of the input.

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    placeholder: "Search for products",
  });
  ```
</ParamField>

<ParamField body="autofocus" type="boolean" default={false}>
  Whether the input should be autofocused.

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    autofocus: true,
  });
  ```
</ParamField>

<ParamField body="ignoreCompositionEvents" type="boolean" default={false} post={["since: v4.64.2"]}>
  Whether to update the search state in the middle of a composition session.
  This is useful when users need to search using non-latin characters.

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    ignoreCompositionEvents: true,
  });
  ```
</ParamField>

<ParamField body="searchAsYouType" type="boolean" default={true}>
  If `false`, triggers the search only on submit.

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    searchAsYouType: false,
  });
  ```
</ParamField>

<ParamField body="showReset" type="boolean" default={true}>
  Whether to show the reset button.

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    showReset: false,
  });
  ```
</ParamField>

<ParamField body="showSubmit" type="boolean" default={true}>
  Whether to show the submit button.

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    showSubmit: false,
  });
  ```
</ParamField>

<ParamField body="showLoadingIndicator" type="boolean" default={true}>
  Whether to show the loading indicator (replaces the submit button if the search is stalled).

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    showLoadingIndicator: false,
  });
  ```
</ParamField>

<ParamField body="aiMode" type="boolean" default={false}>
  Whether to show an AI Mode button in the search box.
  When users click this button, it opens the [Chat](/doc/api-reference/widgets/chat/js) widget and sends the current query.

  To use this option, add a `chat()` widget on the same index.
  For an end-to-end walkthrough, see [Build an AI-powered search experience](/doc/guides/building-search-ui/going-further/chat-customization/ai-search-experience/js).

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    aiMode: true,
  });
  ```
</ParamField>

<ParamField body="queryHook" type="function">
  A function that is called just before the search is triggered. It takes two parameters:

  * `query: string`: the current query string
  * `search: function`: a function to trigger the search.

  If the `search` method is not called, no search is made to Algolia and the UI doesn't refresh. If the `search` method is called, the widget is rendered.

  This can be useful if you need to:

  * Debounce the number of searches done from the `searchBox`.
    You can find more information in [the guide on slow network](/doc/guides/building-search-ui/going-further/improve-performance/js).
  * Programmatically alter the query.

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    queryHook(query, search) {
      search(query);
    },
  });
  ```
</ParamField>

<ParamField body="templates" type="object">
  The [templates](#templates) to use for the widget.

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    templates: {
      // ...
    },
  });
  ```
</ParamField>

<ParamField body="cssClasses" type="object">
  The [CSS classes you can override](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js#style-your-widgets):

  * `root`: the root element of the widget.
  * `form`: the form element.
  * `input`: the input element.
  * `reset`: the reset button element.
  * `resetIcon`: the reset button icon.
  * `loadingIndicator`: the loading indicator element.
  * `loadingIcon`: the loading indicator icon.
  * `submit`: the submit button element.
  * `submitIcon`: the submit button icon.
  * `aiModeButton`: the AI mode button.
  * `aiModeIcon`: the AI mode icon.
  * `aiModeLabel`: the AI mode label.

  ```js JavaScript icon=code theme={"system"}
  searchBox({
    // ...
    cssClasses: {
      root: "MyCustomSearchBox",
      form: ["MyCustomSearchBoxForm", "MyCustomSearchBoxForm--subclass"],
    },
  });
  ```
</ParamField>

## Templates

You can customize parts of a widget’s UI using the Templates API.

Each template includes an `html` function,
which you can use as a [tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates).
This function safely renders templates as HTML strings and works directly in the browser—no build step required.
For details, see [Templating your UI](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js/#templating-your-ui).

<Note>
  The `html` function is available in InstantSearch.js version 4.46.0 or later.
</Note>

<ParamField body="submit" type="string | function">
  The template used for displaying the submit button.

  <CodeGroup>
    ```js function theme={"system"}
    searchBox({
      // ...
      templates: {
        submit({ cssClasses }, { html }) {
          return html`<span class="${cssClasses.submit}">submit</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    searchBox({
      // ...
      templates: {
        submit: "submit",
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="reset" type="string | function">
  The template used for displaying the reset button.

  <CodeGroup>
    ```js function theme={"system"}
    searchBox({
      // ...
      templates: {
        reset({ cssClasses }, { html }) {
          return html`<span class="${cssClasses.reset}">reset</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    searchBox({
      // ...
      templates: {
        reset: "reset",
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="loadingIndicator" type="string | function">
  The template used for displaying the loading indicator.

  <CodeGroup>
    ```js function theme={"system"}
    searchBox({
      // ...
      templates: {
        loadingIndicator({ cssClasses }, { html }) {
          return html`<span class="${cssClasses.loadingIndicator}">loading</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    searchBox({
      // ...
      templates: {
        loadingIndicator: "loading",
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="aiMode" type="string | function">
  The template used for displaying the AI Mode button.

  <CodeGroup>
    ```js function theme={"system"}
    searchBox({
      // ...
      templates: {
        aiMode({ cssClasses }, { html }) {
          return html`<span class="${cssClasses.aiModeLabel}">Ask AI</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    searchBox({
      // ...
      templates: {
        aiMode: "Ask AI",
      },
    });
    ```
  </CodeGroup>
</ParamField>

## HTML output

```html HTML icon=code-xml theme={"system"}
<div class="ais-SearchBox">
  <form class="ais-SearchBox-form" novalidate>
    <input
      class="ais-SearchBox-input"
      autocomplete="off"
      autocorrect="off"
      autocapitalize="off"
      placeholder="Search for products"
      spellcheck="false"
      maxlength="512"
      type="search"
      value=""
    />
    <button
      class="ais-SearchBox-submit"
      type="submit"
      title="Submit the search query."
    >
      <svg
        class="ais-SearchBox-submitIcon"
        xmlns="http://www.w3.org/2000/svg"
        width="10"
        height="10"
        viewBox="0 0 40 40"
      >
        ...
      </svg>
    </button>
    <button
      class="ais-SearchBox-reset"
      type="reset"
      title="Clear the search query."
      hidden
    >
      <svg
        class="ais-SearchBox-resetIcon"
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 20 20"
        width="10"
        height="10"
      >
        ...
      </svg>
    </button>
    <span class="ais-SearchBox-loadingIndicator" hidden>
      <svg
        width="16"
        height="16"
        viewBox="0 0 38 38"
        xmlns="http://www.w3.org/2000/svg"
        stroke="#444"
        class="ais-SearchBox-loadingIcon"
      >
        ...
      </svg>
    </span>
    <button
      class="ais-AiModeButton"
      type="button"
      title="AI Mode"
    >
      <svg class="ais-AiModeButton-icon" viewBox="0 0 24 24">
        ...
      </svg>
      <span class="ais-AiModeButton-label">AI Mode</span>
    </button>
  </form>
</div>
```

## Customize the UI with `connectSearchBox`

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

To use `connectSearchBox`, you can import it with the declaration relevant to how you installed InstantSearch.js.

<CodeGroup>
  ```js Package manager theme={"system"}
  import { connectSearchBox } from "instantsearch.js/es/connectors";
  ```

  ```js CDN theme={"system"}
  const { connectSearchBox } = instantsearch.connectors;
  // or directly use instantsearch.connectors.connectSearchBox()
  ```
</CodeGroup>

Then it's a 3-step process:

```js JavaScript icon=code theme={"system"}
// 1. Create a render function
const renderSearchBox = (renderOptions, isFirstRender) => {
  // Rendering logic
};

// 2. Create the custom widget
const customSearchBox = connectSearchBox(renderSearchBox);

// 3. Instantiate
search.addWidgets([
  customSearchBox({
    // 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).

```js JavaScript icon=code theme={"system"}
const renderSearchBox = (renderOptions, isFirstRender) => {
  const { query, refine, clear, isSearchStalled, widgetParams } = renderOptions;

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

  // Render the widget
};
```

#### Render options

<ParamField body="query" type="string">
  The query from the current search.

  ```js JavaScript icon=code theme={"system"}
  const renderSearchBox = (renderOptions, isFirstRender) => {
    const { query, refine } = renderOptions;

    const container = document.querySelector("#searchbox");

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

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

      container.appendChild(input);
    }

    container.querySelector("input").value = query;
  };
  ```
</ParamField>

<ParamField body="refine" type="function">
  Sets a new query and triggers a new search.

  ```js JavaScript icon=code theme={"system"}
  const renderSearchBox = (renderOptions, isFirstRender) => {
    const { query, refine } = renderOptions;

    const container = document.querySelector("#searchbox");

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

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

      container.appendChild(input);
    }

    container.querySelector("input").value = query;
  };
  ```
</ParamField>

<ParamField body="clear" type="function">
  Removes the query and triggers a new search.

  ```js JavaScript icon=code theme={"system"}
  const renderSearchBox = (renderOptions, isFirstRender) => {
    const { query, refine, clear } = renderOptions;

    const container = document.querySelector("#searchbox");

    if (isFirstRender) {
      const input = document.createElement("input");
      const button = document.createElement("button");
      button.textContent = "X";

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

      button.addEventListener("click", () => {
        clear();
      });

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

    container.querySelector("input").value = query;
  };
  ```
</ParamField>

<ParamField body="isSearchStalled" type="boolean">
  Returns `true` if the search results take more than a certain time to come back from Algolia servers.
  This can be configured on the [`instantsearch`](/doc/api-reference/widgets/instantsearch/js)
  constructor with the attribute `stalledSearchDelay`.

  ```js JavaScript icon=code theme={"system"}
  const renderSearchBox = (renderOptions, isFirstRender) => {
    const { query, refine, isSearchStalled } = renderOptions;

    const container = document.querySelector("#searchbox");

    if (isFirstRender) {
      const input = document.createElement("input");
      const loadingIndicator = document.createElement("span");
      loadingIndicator.textContent = "Loading...";

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

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

    container.querySelector("input").value = query;
    container.querySelector("span").hidden = !isSearchStalled;
  };
  ```
</ParamField>

<ParamField body="widgetParams" type="object">
  All original widget options forwarded to the render function.

  ```js JavaScript icon=code theme={"system"}
  const renderRangeInput = (renderOptions, isFirstRender) => {
    const { widgetParams } = renderOptions;

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

  // ...

  search.addWidgets([
    customRangeInput({
      container: document.querySelector("#searchbox"),
    }),
  ]);
  ```
</ParamField>

### 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`.

```js JavaScript icon=code theme={"system"}
const customSearchBox = connectSearchBox(renderSearchBox);

search.addWidgets([
  customSearchBox({
    // Optional parametersqueryHook:function,
  }),
]);
```

#### Instance options

<ParamField body="queryHook" type="function">
  A function that is called just before the search is triggered. It takes two parameters

  * `query: string`: the current query string
  * `search: function`: a function to trigger the search.

  If the `search` method is not called, no search is made to Algolia and the UI doesn't refresh.
  If the `search` method is called, the widget is rendered.

  This can be useful if you need to:

  * debounce the number of searches done from the `searchBox`.
    You can find more information in [the guide on slow network](/doc/guides/building-search-ui/going-further/improve-performance/js).
  * programmatically alter the query.

  ```js JavaScript icon=code theme={"system"}
  customSearchBox({
    queryHook(query, search) {
      search(query);
    },
  });
  ```
</ParamField>

### Full example

<CodeGroup>
  ```html HTML theme={"system"}
  <div id="searchbox"></div>
  ```

  ```js JavaScript theme={"system"}
  // Create a render function
  const renderSearchBox = (renderOptions, isFirstRender) => {
    const { query, refine, clear, isSearchStalled, widgetParams } = renderOptions;

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

      const loadingIndicator = document.createElement("span");
      loadingIndicator.textContent = "Loading...";

      const button = document.createElement("button");
      button.textContent = "X";

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

      button.addEventListener("click", () => {
        clear();
      });

      widgetParams.container.appendChild(input);
      widgetParams.container.appendChild(loadingIndicator);
      widgetParams.container.appendChild(button);
    }

    widgetParams.container.querySelector("input").value = query;
    widgetParams.container.querySelector("span").hidden = !isSearchStalled;
  };

  // Create custom widget
  const customSearchBox = connectSearchBox(renderSearchBox);

  // Instantiate custom widget
  search.addWidgets([
    customSearchBox({
      container: document.querySelector("#searchbox"),
    }),
  ]);
  ```
</CodeGroup>
