UI libraries / React InstantSearch / Widgets

This is the React InstantSearch v7 documentation. React InstantSearch v7 is the latest version of React InstantSearch and the stable version of React InstantSearch Hooks.

If you were using React InstantSearch v6, you can upgrade to v7.

If you were using React InstantSearch Hooks, you can still use the React InstantSearch v7 documentation, but you should check the upgrade guide for necessary changes.

If you want to keep using React InstantSearch v6, you can find the archived documentation.

Signature
<SearchBox
  // Optional props
  placeholder={string}
  queryHook={function}
  ignoreCompositionEvents={boolean}
  searchAsYouType={boolean}
  autoFocus={boolean}
  onSubmit={function}
  submitIconComponent={() => JSX.Element}
  resetIconComponent={() => JSX.Element}
  loadingIconComponent={() => JSX.Element}
  classNames={object}
  translations={object}
  ...props={ComponentProps<'div'>}
/>
Import
1
import { SearchBox } from 'react-instantsearch';

About this widget

<SearchBox> is a widget to let users perform a text-based query.

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.

You can also create your own UI with useSearchBox().

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';
import 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

Parameter Description
placeholder
type: string
Optional

The placeholder text of the input.

1
<SearchBox placeholder="Search for products" />
queryHook
type: (query: string, search: (value: string) => void) => void
Optional

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.

1
2
3
4
5
6
7
const queryHook = (query, search) => {
  search(query);
};

function Search() {
  return <SearchBox queryHook={queryHook} />;
}
ignoreCompositionEvents
since: v7.5.4
type: boolean
default: false
Optional

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.

1
<SearchBox ignoreCompositionEvents />
searchAsYouType
type: boolean
default: true
Optional

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.

1
<SearchBox searchAsYouType={false} />
autoFocus
type: boolean
default: false
Optional

Whether the input should be autofocused.

1
<SearchBox autoFocus />
onSubmit
type: (event: React.FormEvent<HTMLFormElement>) => void
Optional

A callback to run when submitting the form of the search box.

1
2
3
4
5
<SearchBox
  onSubmit={(event) => {
    // Code to run when the form submits
  }}
/>
submitIconComponent
type: (props: IconProps) => JSX.Element
Optional

A component to replace the icon in the submit button.

The component receives the passed classNames prop.

1
2
3
4
5
<SearchBox
  submitIconComponent={({ classNames }) => (
    <div className={classNames.submitIcon}>Submit</div>
  )}
/>
resetIconComponent
type: (props: IconProps) => JSX.Element
Optional

A component to replace the icon in the reset button.

The component receives the passed classNames prop.

1
2
3
4
5
<SearchBox
  resetIconComponent={({ classNames }) => (
    <div className={classNames.resetIcon}>Reset</div>
  )}
/>
loadingIconComponent
type: (props: IconProps) => JSX.Element
Optional

A component to replace the loading icon.

The component receives the passed classNames prop.

1
2
3
4
5
<SearchBox
  loadingIconComponent={({ classNames }) => (
    <div className={classNames.loadingIcon}>Loading</div>
  )}
/>
classNames
type: Partial<SearchBoxClassNames>
Optional

The CSS classes you can override and pass to the widget’s elements. It’s useful to style widgets with class-based CSS frameworks like Bootstrap or Tailwind CSS.

  • 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.
1
2
3
4
5
6
<SearchBox
  classNames={{
    root: 'MyCustomSearchBox',
    form: 'MyCustomSearchBoxForm MyCustomSearchBoxForm--subclass',
  }}
/>
translations
type: Partial<SearchBoxTranslations>
Optional

A dictionary of translations to customize the UI text and support internationalization.

  • submitTitle: The submit button’s title.
  • resetTitle: The reset button’s title.
1
2
3
4
5
6
<SearchBox
  translations={{
    submitTitle: 'Search',
    resetTitle: 'Reset',
  }}
/>
...props
type: React.ComponentProps<'div'>
Optional

Any <div> prop to forward to the root element of the widget.

1
<SearchBox className="MyCustomSearchBox" title="My custom title" />

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 and returns APIs.

Usage

First, create your React component:

import { useSearchBox } from 'react-instantsearch';

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

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

Then, render the widget:

<CustomSearchBox {...props} />

Parameters

Hooks accept parameters. You can pass them manually, or forward the props from your custom component.

When you provide a function to Hooks, make sure to pass a stable reference to avoid rendering endlessly (for example, with useCallback()). Objects and arrays are memoized; you don’t need to stabilize them.

Parameter Description
queryHook
type: (query: string, hook: (value: string) => void) => void
Optional

Function called every time the query changes.

See queryHook for detail.

1
2
3
4
5
6
7
8
9
10
11
12
const queryHook = (query, search) => {
  search(query);
};

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

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

APIs

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

Parameter Description
query
type: string

The query from the last search.

refine
type: (value: string) => void

Sets a new query and searches.

clear
type: () => void

Clears the query and searches.

isSearchStalled
Deprecated
type: boolean

Use status from useInstantSearch() instead.

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

This can be configured on <InstantSearch> with the stalledSearchDelay props which defaults to 200 ms.

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
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>
  );
}
Did you find this page helpful?