> ## 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">React</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="false"><a className="afs-option" 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="true"><a className="afs-option is-current" 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>

<Note>
  This is the **React InstantSearch v7** documentation.
  If you're upgrading from v6, see the [upgrade guide](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-v6-to-react-instantsearch-v7).
  If you were using React InstantSearch Hooks,
  this v7 documentation applies—just check for [necessary changes](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-hooks-to-react-instantsearch-v7).
  To continue using v6, you can find the [archived documentation](https://algolia.com/old-docs/deprecated/instantsearch/react/v6/api-reference/instantsearch/).
</Note>

```tsx Signature theme={"system"}
<SearchBox
  // Optional props
  placeholder={string}
  queryHook={function}
  ignoreCompositionEvents={boolean}
  searchAsYouType={boolean}
  aiMode={boolean}
  autoFocus={boolean}
  onSubmit={function}
  submitIconComponent={() => JSX.Element}
  resetIconComponent={() => JSX.Element}
  loadingIconComponent={() => JSX.Element}
  aiModeIconComponent={() => JSX.Element}
  classNames={object}
  translations={object}
  ...props={ComponentProps<'div'>}
/>
```

## Import

```jsx JavaScript icon=code theme={"system"}
import { SearchBox } from "react-instantsearch";
```

<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

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

The search box usually is the main entry point to start the search on an InstantSearch page.
You typically place it at the top of a search experience so that users can start searching right away.

<Tip>
  You can also create your own UI with [`useSearchBox`](#hook).
</Tip>

## Examples

```jsx JavaScript icon=code theme={"system"}
import React from "react";
import { liteClient as algoliasearch } from "algoliasearch/lite";
import { InstantSearch, SearchBox } from "react-instantsearch";

const searchClient = algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey");

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <SearchBox />
    </InstantSearch>
  );
}
```

## Props

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

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox placeholder="Search for products" />;
  ```
</ParamField>

<ParamField body="queryHook" type="(query: string, search: (value: string) => void) => void">
  Function called every time the query changes. It takes two parameters:

  * `query`: The current query.
  * `search`: The function to trigger the search.

  This prop can be useful if you need to:

  * Debounce searches to regulate requests.
  * Programmatically alter the query before sending it to Algolia.

  When using this prop, you're responsible for triggering the search with `search`.
  If you don't call this function, no search is triggered to Algolia.

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    const queryHook = (query, search) => {
      search(query);
    };

    function Search() {
      return <SearchBox queryHook={queryHook} />;
    }
    ```

    ```tsx TypeScript theme={"system"}
    import type { SearchBoxProps } from "react-instantsearch";

    const queryHook: SearchBoxProps["queryHook"] = (query, search) => {
      search(query);
    };

    function Search() {
      return <SearchBox queryHook={queryHook} />;
    }
    ```
  </CodeGroup>
</ParamField>

<ParamField body="ignoreCompositionEvents" type="boolean" default={false} post={["since: v7.5.4"]}>
  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.

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox ignoreCompositionEvents />;
  ```
</ParamField>

<ParamField body="searchAsYouType" type="boolean" default={true}>
  Whether to make a search on every change to the query.
  If `false`, new searches are only triggered by clicking the search button or by pressing the `Enter` key while focusing the search box.

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox searchAsYouType={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/react) widget and sends the current query.

  To use this prop, 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/react).

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox aiMode />;
  ```
</ParamField>

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

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox autoFocus />;
  ```
</ParamField>

<ParamField body="onSubmit" type="(event: React.FormEvent<HTMLFormElement>) => void">
  A callback to run when submitting the form of the search box.

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox
    onSubmit={(event) => {
      // Code to run when the form submits
    }}
  />;
  ```
</ParamField>

<ParamField body="submitIconComponent" type="(props: IconProps) => JSX.Element">
  A component to replace the icon in the submit button.

  The component receives the passed [`classNames`](/doc/api-reference/widgets/search-box/react#param-class-names) prop.

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox
    submitIconComponent={({ classNames }) => (
      <div className={classNames.submitIcon}>Submit</div>
    )}
  />;
  ```
</ParamField>

<ParamField body="resetIconComponent" type="(props: IconProps) => JSX.Element">
  A component to replace the icon in the reset button.

  The component receives the passed [`classNames`](/doc/api-reference/widgets/search-box/react#param-class-names) prop.

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox
    resetIconComponent={({ classNames }) => (
      <div className={classNames.resetIcon}>Reset</div>
    )}
  />;
  ```
</ParamField>

<ParamField body="loadingIconComponent" type="(props: IconProps) => JSX.Element">
  A component to replace the loading icon.

  The component receives the passed [`classNames`](/doc/api-reference/widgets/search-box/react#param-class-names) prop.

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox
    loadingIconComponent={({ classNames }) => (
      <div className={classNames.loadingIcon}>Loading</div>
    )}
  />;
  ```
</ParamField>

<ParamField body="aiModeIconComponent" type="(props: IconProps) => JSX.Element">
  A component to replace the icon in the AI Mode button.

  The component receives the passed [`classNames`](/doc/api-reference/widgets/search-box/react#param-class-names) prop.

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox
    aiMode
    aiModeIconComponent={({ classNames }) => (
      <div className={classNames.aiModeIcon}>AI</div>
    )}
  />;
  ```
</ParamField>

<ParamField body="classNames" type="Partial<SearchBoxClassNames>">
  The [CSS classes you can override](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/react#style-your-widgets) and pass to the widget's elements.
  It's useful to style widgets with class-based CSS frameworks like [Bootstrap](https://getbootstrap.com) or [Tailwind CSS](https://tailwindcss.com).

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

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox
    classNames={{
      root: "MyCustomSearchBox",
      form: "MyCustomSearchBoxForm MyCustomSearchBoxForm--subclass",
    }}
  />;
  ```
</ParamField>

<ParamField body="translations" type="Partial<SearchBoxTranslations>">
  A dictionary of translations to customize the UI text and support internationalization.

  * `submitButtonTitle`. The submit button's title.
  * `resetButtonTitle`. The reset button's title.
  * `aiModeButtonTitle`. The AI mode button's title.

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox
    translations={{
      submitButtonTitle: "Search",
      resetButtonTitle: "Reset",
      aiModeButtonTitle: "Ask AI",
    }}
  />;
  ```
</ParamField>

<ParamField body="...props" type="React.ComponentProps<'div'>">
  Any `<div>` prop to forward to the root element of the widget.

  ```jsx JavaScript icon=code theme={"system"}
  <SearchBox className="MyCustomSearchBox" title="My custom title" />;
  ```
</ParamField>

## Hook

React InstantSearch let you create your own UI for the `<SearchBox>` widget with `useSearchBox`.
Hooks provide APIs to access the widget state and interact with InstantSearch.

The `useSearchBox` Hook accepts [parameters](#parameters) and returns [APIs](#hook).
It must be used inside the [`<InstantSearch>`](/doc/api-reference/widgets/instantsearch/react) component.

### Usage

First, create your React component:

```jsx JavaScript icon=code theme={"system"}
import { useSearchBox } from "react-instantsearch";

function CustomSearchBox(props) {
  const { query, refine, clear } = useSearchBox(props);

  return <>{/*Your JSX*/}</>;
}
```

Then, render the widget:

```jsx JavaScript icon=code theme={"system"}
<CustomSearchBox {...props} />;
```

### Parameters

Hooks accept parameters. You can either pass them manually or forward props from a custom component.

<Note>
  When passing functions to Hooks, ensure stable references to prevent unnecessary re-renders.
  Use [`useCallback()`](https://reactjs.org/docs/hooks-reference.html#usecallback) for memoization.
  Arrays and objects are automatically memoized.
</Note>

<ParamField body="queryHook" type="(query: string, hook: (value: string) => void) => void">
  Function called every time the query changes.

  See [`queryHook`](/doc/api-reference/widgets/search-box/react#param-query-hook) for detail.

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    const queryHook = (query, search) => {
      search(query);
    };

    function SearchBox() {
      const searchBoxApi = useSearchBox({
        // ...
        queryHook,
      });

      return <>{/*Your JSX*/}</>;
    }
    ```

    ```tsx TypeScript theme={"system"}
    import type { UseSearchBoxProps } from "react-instantsearch";

    const queryHook: UseSearchBoxProps["queryHook"] = (query, search) => {
      search(query);
    };

    function SearchBox() {
      const searchBoxApi = useSearchBox({
        // ...
        queryHook,
      });

      return <>{/* Your JSX */}</>;
    }
    ```
  </CodeGroup>
</ParamField>

### APIs

Hooks return APIs, such as state and functions. You can use them to build your UI and interact with React InstantSearch.

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

<ParamField body="refine" type="(value: string) => void">
  Sets a new query and searches.
</ParamField>

<ParamField body="clear" type="() => void">
  Clears the query and searches.
</ParamField>

<ParamField body="isSearchStalled" type="boolean" deprecated>
  > Use `status` from [`useInstantSearch`](/doc/api-reference/widgets/use-instantsearch/react) instead.

  Whether the search results take more than a certain time to come back from Algolia servers.

  This can be configured on [`<InstantSearch>`](/doc/api-reference/widgets/instantsearch/react) with the `stalledSearchDelay` props which defaults to 200 ms.
</ParamField>

### Example

<CodeGroup>
  ```jsx JavaScript theme={"system"}
  import React, { useState, useRef } from "react";
  import { useInstantSearch, useSearchBox } from "react-instantsearch";

  function CustomSearchBox(props) {
    const { query, refine } = useSearchBox(props);
    const { status } = useInstantSearch();
    const [inputValue, setInputValue] = useState(query);
    const inputRef = useRef(null);

    const isSearchStalled = status === "stalled";

    function setQuery(newQuery) {
      setInputValue(newQuery);

      refine(newQuery);
    }

    return (
      <div>
        <form
          action=""
          role="search"
          noValidate
          onSubmit={(event) => {
            event.preventDefault();
            event.stopPropagation();

            if (inputRef.current) {
              inputRef.current.blur();
            }
          }}
          onReset={(event) => {
            event.preventDefault();
            event.stopPropagation();

            setQuery("");

            if (inputRef.current) {
              inputRef.current.focus();
            }
          }}
        >
          <input
            ref={inputRef}
            autoComplete="off"
            autoCorrect="off"
            autoCapitalize="off"
            placeholder="Search for products"
            spellCheck={false}
            maxLength={512}
            type="search"
            value={inputValue}
            onChange={(event) => {
              setQuery(event.currentTarget.value);
            }}
            autoFocus
          />
          <button type="submit">Submit</button>
          <button
            type="reset"
            hidden={inputValue.length === 0 || isSearchStalled}
          >
            Reset
          </button>
          <span hidden={!isSearchStalled}>Searching…</span>
        </form>
      </div>
    );
  }
  ```

  ```tsx TypeScript theme={"system"}
  import React, { useState, useRef } from "react";
  import {
    useInstantSearch,
    useSearchBox,
    UseSearchBoxProps,
  } from "react-instantsearch";

  function CustomSearchBox(props: UseSearchBoxProps) {
    const { query, refine } = useSearchBox(props);
    const { status } = useInstantSearch();
    const [inputValue, setInputValue] = useState(query);
    const inputRef = useRef<HTMLInputElement>(null);

    const isSearchStalled = status === "stalled";

    function setQuery(newQuery: string) {
      setInputValue(newQuery);

      refine(newQuery);
    }

    return (
      <div>
        <form
          action=""
          role="search"
          noValidate
          onSubmit={(event) => {
            event.preventDefault();
            event.stopPropagation();

            if (inputRef.current) {
              inputRef.current.blur();
            }
          }}
          onReset={(event) => {
            event.preventDefault();
            event.stopPropagation();

            setQuery("");

            if (inputRef.current) {
              inputRef.current.focus();
            }
          }}
        >
          <input
            ref={inputRef}
            autoComplete="off"
            autoCorrect="off"
            autoCapitalize="off"
            placeholder="Search for products"
            spellCheck={false}
            maxLength={512}
            type="search"
            value={inputValue}
            onChange={(event) => {
              setQuery(event.currentTarget.value);
            }}
            autoFocus
          />
          <button type="submit">Submit</button>
          <button
            type="reset"
            hidden={inputValue.length === 0 || isSearchStalled}
          >
            Reset
          </button>
          <span hidden={!isSearchStalled}>Searching…</span>
        </form>
      </div>
    );
  }
  ```
</CodeGroup>
