🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
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
<ToggleRefinement
  attribute={string}
  // Optional parameters
  label={string}
  on={boolean | number | string}
  off={boolean | number | string}
  classNames={object}
  ...props={ComponentProps<'div'>}
/>
Import
1
import { ToggleRefinement } from 'react-instantsearch';

About this widget

<ToggleRefinement> is a widget that provides an on/off filter based on an attribute value.

For example, you can use this widget to only display products that apply for free shipping, or recipes that are gluten-free.

Make sure to declare the provided attribute as an attribute for faceting.

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

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, ToggleRefinement } from 'react-instantsearch';

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

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <ToggleRefinement attribute="free_shipping" />
    </InstantSearch>
  );
}

Props

Parameter Description
attribute
type: string
Required

The name of the attribute in the records.

To avoid unexpected behavior, you can’t use the same attribute prop in a different type of widget.

1
<ToggleRefinement attribute="free_shipping" />
label
type: string
Optional

The label to display for the checkbox.

1
2
3
4
<ToggleRefinement
  // ...
  label="Free shipping"
/>
on
type: boolean|string|number
Optional

The value of the refinement to apply on the attribute when checked.

1
2
3
4
<ToggleRefinement
  // ...
  on={true}
/>
off
type: boolean|string|number
Optional

The value of the refinement to apply on the attribute when unchecked.

1
2
3
4
<ToggleRefinement
  // ...
  off={false}
/>
classNames
type: Partial<ToggleRefinementClassNames>
Optional

CSS classes to pass to the widget’s elements. This is useful to style widgets with class-based CSS frameworks like Bootstrap or Tailwind CSS.

  • root: The root element of the widget.
  • label: The label element.
  • checkbox: The checkbox element.
  • labelText: The text element of the label.
1
2
3
4
5
6
7
<ToggleRefinement
  // ...
  classNames={{
    root: 'MyCustomToggleRefinement',
    checkbox: 'MyCustomToggleRefinementCheckbox MyCustomToggleRefinementCheckbox--subclass',
  }}
/>
...props
type: React.ComponentProps<'div'>
Optional

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

1
2
3
4
5
<ToggleRefinement
  // ...
  className="MyCustomToggleRefinement"
  title="My custom title"
/>

Hook

React InstantSearch let you create your own UI for the <ToggleRefinement> widget with useToggleRefinement(). Hooks provide APIs to access the widget state and interact with InstantSearch.

The useToggleRefinement() Hook accepts parameters and returns APIs.

Usage

First, create your React component:

import { useToggleRefinement } from 'react-instantsearch';

function CustomToggleRefinement(props) {
  const {
    value,
    canRefine,
    refine,
    sendEvent,
    createURL,
  } = useToggleRefinement(props);

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

Then, render the widget:

<CustomToggleRefinement {...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
attribute
type: string
Required

The name of the attribute in the records.

To avoid unexpected behavior, you can’t use the same attribute prop in a different type of widget.

1
2
3
const toggleRefinementApi = useToggleRefinement({
  attribute: 'free_shipping',
});
on
type: boolean|string|number
Optional

The value of the refinement to apply on the attribute when checked.

1
2
3
4
const toggleRefinementApi = useToggleRefinement({
  // ...
  on: true,
});
off
type: boolean|string|number
Optional

The value of the refinement to apply on the attribute when unchecked.

1
2
3
4
const toggleRefinementApi = useToggleRefinement({
  // ...
  off: false,
});

APIs

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

Parameter Description
value
type: ToggleRefinementValue

The current refinement.

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
type ToggleRefinementValue = {
  /**
  * The attribute name of this toggle.
  */
  name: string;
  /**
  * Whether the current option is "on" (true) or "off" (false)
  */
  isRefined: boolean;
  /**
  * Number of results if this option is toggled.
  */
  count: number | null;
  /**
  * Information about the "on" toggle.
  */
  onFacetValue: ToggleRefinementDetails;
  /**
  * Information about the "off" toggle.
  */
  offFacetValue: ToggleRefinementDetails;
};

type ToggleRefinementDetails = {
  /**
  * whether this option is enabled.
  */
  isRefined: boolean;
  /**
  * Number of result if this option is toggled.
  */
  count: number | null;
};
canRefine
type: boolean

Whether the search state can be refined.

1
2
3
const { canRefine } = useToggleRefinement({ attribute: 'free_shipping' });

return <input disabled={!canRefine} type="checkbox" />;
refine
type: ({ isRefined: boolean }) => void

Updates to the next state by applying the toggle refinement.

1
2
3
4
5
6
7
8
const { refine } = useToggleRefinement({ attribute: 'free_shipping' });

return (
  <input
    onChange={event => refine({ isRefined: !event.target.checked })}
    type="checkbox"
  />
);
sendEvent
type: (eventType: string, facetValue: string, eventName?: string) => void

A function to send click events. The click event is automatically sent when calling refine. You can learn more about the insights middleware.

1
2
3
4
5
6
7
8
9
10
11
12
13
sendEvent('click', true);

// This sends a similar payload to the `insights` middleware.
// {
//   eventType: 'click',
//   insightsMethod: 'clickedFilters',
//   payload: {
//     eventName: 'Filter Applied',
//     filters: ['free_shipping:true'],
//     index: '',
//   },
//   widgetType: 'ais.toggleRefinement',
// }
createURL
type: () => string

Generates a URL for the next state.

1
2
3
4
5
6
7
8
9
10
const { createURL, value, refine } = useToggleRefinement({ attribute: 'free_shipping' });

return (
  <a
    href={createURL()}
    onClick={event => refine({ isRefined: !value.isRefined })}
  >
    Link to the next state
  </a>
);

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React from 'react';
import { useToggleRefinement } from 'react-instantsearch';

function CustomToggleRefinement(props) {
  const { value, refine } = useToggleRefinement(props);

  return (
    <label>
      <input
        type="checkbox"
        checked={value.isRefined}
        onChange={(event) => {
          refine({ isRefined: !event.target.checked });
        }}
      />

      <span>{props.attribute}</span>
    </label>
  );
}
Did you find this page helpful?