> ## 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>;

export const FlavorSwitcher = ({current, baseHref = "", options = [], label = "InstantSearch framework"}) => {
  if (options.length === 0) {
    return <div className="not-prose" role="alert" style={{
      margin: "0.25rem 0 1.5rem",
      padding: "0.75rem",
      border: "1px solid #f59e0b",
      borderRadius: "0.625rem",
      color: "inherit",
      fontSize: "0.875rem"
    }}>
        FlavorSwitcher requires at least one option.
      </div>;
  }
  const selected = options.find(option => option.value === current) ?? options[0];
  return <div className="not-prose mint-flavor-switcher">
      <style>{`
        .mint-flavor-switcher {
          --mfs-bg: #ffffff;
          --mfs-bg-hover: #f4f4f5;
          --mfs-bg-current: #eef2ff;
          --mfs-border: #d4d4d8;
          --mfs-fg: #18181b;
          --mfs-muted: #71717a;
          --mfs-accent: #4f46e5;
          position: relative;
          width: min(100%, 19rem);
          margin: 0.25rem 0 1.5rem;
          color: var(--mfs-fg);
          font-size: 0.875rem;
          line-height: 1.25rem;
        }

        .dark .mint-flavor-switcher {
          --mfs-bg: #18181b;
          --mfs-bg-hover: #27272a;
          --mfs-bg-current: #272747;
          --mfs-border: #3f3f46;
          --mfs-fg: #fafafa;
          --mfs-muted: #a1a1aa;
          --mfs-accent: #a5b4fc;
        }

        .mint-flavor-switcher details {
          position: relative;
        }

        .mint-flavor-switcher summary {
          display: flex;
          min-height: 2.75rem;
          box-sizing: border-box;
          align-items: center;
          justify-content: space-between;
          gap: 0.75rem;
          padding: 0.625rem 0.75rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          color: var(--mfs-fg);
          cursor: pointer;
          font-weight: 600;
          list-style: none;
          transition: border-color 150ms ease, box-shadow 150ms ease;
        }

        .mint-flavor-switcher summary::-webkit-details-marker {
          display: none;
        }

        .mint-flavor-switcher summary:hover {
          border-color: var(--mfs-accent);
        }

        .mint-flavor-switcher summary:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: 2px;
        }

        .mint-flavor-switcher__label {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .mint-flavor-switcher__chevron {
          flex: none;
          transition: transform 150ms ease;
        }

        .mint-flavor-switcher details[open] .mint-flavor-switcher__chevron {
          transform: rotate(180deg);
        }

        .mint-flavor-switcher__menu {
          position: absolute;
          z-index: 50;
          top: calc(100% + 0.375rem);
          left: 0;
          width: 100%;
          box-sizing: border-box;
          margin: 0;
          padding: 0.375rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          box-shadow: 0 12px 30px rgb(0 0 0 / 16%);
          list-style: none;
        }

        .mint-flavor-switcher__menu li {
          margin: 0;
          padding: 0;
        }

        .mint-flavor-switcher__option {
          display: grid;
          gap: 0.125rem;
          padding: 0.625rem 0.75rem;
          border-radius: 0.4rem;
          color: var(--mfs-fg);
          text-decoration: none;
        }

        .mint-flavor-switcher__option:hover {
          background: var(--mfs-bg-hover);
        }

        .mint-flavor-switcher__option:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: -2px;
        }

        .mint-flavor-switcher__option[aria-current="page"] {
          background: var(--mfs-bg-current);
          color: var(--mfs-accent);
        }

        .mint-flavor-switcher__name {
          font-weight: 600;
        }

        .mint-flavor-switcher__description {
          color: var(--mfs-muted);
          font-size: 0.8125rem;
        }

        @media (prefers-reduced-motion: reduce) {
          .mint-flavor-switcher summary,
          .mint-flavor-switcher__chevron {
            transition: none;
          }
        }
      `}</style>

      <details>
        <summary aria-label={`${label}: ${selected.label}`}>
          <span className="mint-flavor-switcher__label">{selected.label}</span>
          <svg className="mint-flavor-switcher__chevron" width="18" height="18" 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>
        </summary>

        <ul className="mint-flavor-switcher__menu" aria-label={label}>
          {options.map(option => {
    const isCurrent = option.value === selected.value;
    const href = option.href ?? `${baseHref.replace(/\/$/, "")}/${encodeURIComponent(option.value)}`;
    return <li key={option.value}>
                <a className="mint-flavor-switcher__option" href={href} aria-current={isCurrent ? "page" : undefined}>
                  <span className="mint-flavor-switcher__name">
                    {option.label}
                  </span>
                  {option.description ? <span className="mint-flavor-switcher__description">
                      {option.description}
                    </span> : null}
                </a>
              </li>;
  })}
        </ul>
      </details>
    </div>;
};

<div className="mint-flavor-switcher-slot not-prose">
  <FlavorSwitcher
    current="js"
    baseHref="/doc/api-reference/widgets/search-box"
    options={[
{ value: "js", label: "JavaScript", description: "InstantSearch.js" },
{ value: "react", label: "React", description: "React InstantSearch" },
{ value: "vue", label: "Vue", description: "Vue InstantSearch" },
{ value: "ios", label: "iOS", description: "InstantSearch iOS" },
{ value: "android", label: "Android", description: "InstantSearch Android" },
]}
  />
</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>
