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

# queryRuleContext

> Applies rule contexts based on applied filters for triggering context-dependent rules.

```ts Signature theme={"system"}
queryRuleContext({
  trackedFilters: object,
  // Optional parameters
  transformRuleContexts?: function,
});
```

## Import

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

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

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

## About this widget

The `queryRuleContext` widget lets you apply [`ruleContexts`](/doc/api-reference/api-parameters/ruleContexts)
based on filters to trigger context-dependent [rules](/doc/guides/managing-results/rules/rules-overview).

Rules offer a custom experience based on contexts.
You might want to customize the users' experience based on the filters of the search
(for example, they're visiting the "Mobile" category, they selected the "Thriller" genre, etc.)
This widget lets you map these filters to their associated rule contexts,
so you can trigger context-based rules on refinement.

## Examples

```js JavaScript icon=code theme={"system"}
queryRuleContext({
  trackedFilters: {
    genre: () => ["Comedy", "Thriller"],
    rating: (values) => values,
  },
});
```

## Options

<ParamField body="trackedFilters" type="object" required>
  The filters to track to trigger rule contexts.

  Each filter is a function which name is the attribute you want to track.
  They receive their current refinements as arguments.
  You can either compute the filters you want to track based on those, or return static values.
  When the tracked values are refined, it toggles the associated rule contexts.

  The added rule contexts follow the format `ais-{attribute}-{value}` (for example `ais-genre-Thriller`).
  If the context of your rule follows another format,
  you can specify it using the [`transformRuleContexts`](/doc/api-reference/widgets/query-rule-context/js#param-transform-rule-contexts) option.

  Values are escaped so that they only consist of alphanumeric characters, hyphens, and underscores.

  ```js JavaScript icon=code theme={"system"}
  queryRuleContext({
    trackedFilters: {
      genre: () => ["Comedy", "Thriller"], // this tracks two static genre values,
      rating: (values) => values, // this tracks all the rating values
    },
  });
  ```
</ParamField>

<ParamField body="transformRuleContexts" type="function">
  A function to apply to the rule contexts before sending them to Algolia.
  This is useful to rename rule contexts that follow a different naming convention.

  ```js JavaScript icon=code theme={"system"}
  queryRuleContext({
    // ...
    transformRuleContexts(ruleContexts) {
      return ruleContexts.map((ruleContext) =>
        ruleContext.replace("ais-", "custom-"),
      );
    },
  });
  ```
</ParamField>

## Customize the UI with `connectQueryRules`

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

<Info>
  This connector is also used to build the [`queryRuleCustomData`](/doc/api-reference/widgets/query-rule-custom-data/js) widget.
</Info>

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

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

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

Then it's a 3-step process:

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

// 2. Create the custom widget
const customQueryRuleContext = connectQueryRules(renderQueryRuleContext);

// 3. Instantiate
search.addWidgets([
  customQueryRuleContext({
    // 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 renderQueryRuleContext = (renderOptions, isFirstRender) => {
  const { widgetParams } = renderOptions;

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

  // Render the widget
};
```

#### Render options

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

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

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

  // ...

  search.addWidgets([
    customQueryRuleContext({
      container: document.querySelector("#queryRuleContext"),
    }),
  ]);
  ```
</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 customQueryRuleContext = connectQueryRules(renderQueryRuleContext);

search.addWidgets([
  customQueryRuleContext({
    // Optional parameters
    trackedFilters,
    transformRuleContexts,
  }),
]);
```

#### Instance options

<ParamField body="trackedFilters" type="object">
  The filters to track to trigger Rule contexts.

  Each filter is a function which name is the attribute you want to track.
  They receive their current refinements as arguments.
  You can either compute the filters you want to track based on those, or return static values.
  When the tracked values are refined, it toggles the associated rule contexts.

  The added rule contexts follow the format `ais-{attribute}-{value}` (for example `ais-genre-Thriller`).
  If the context of your rule follows another format,
  you can specify it using the [`transformRuleContexts`](/doc/api-reference/widgets/query-rule-context/js#param-transform-rule-contexts) option.

  Values are escaped so that they only consist of alphanumeric characters, hyphens, and underscores.

  ```js JavaScript icon=code theme={"system"}
  customQueryRuleContext({
    trackedFilters: {
      genre: () => ["Comedy", "Thriller"], // this tracks two static genre values,
      rating: (values) => values, // this tracks all the rating values
    },
  });
  ```
</ParamField>

<ParamField body="transformRuleContexts" type="function">
  A function to apply to the rule contexts before sending them to Algolia.
  This is useful to rename rule contexts that follow a different naming convention.

  ```js JavaScript icon=code theme={"system"}
  customQueryRuleContext({
    // ...
    transformRuleContexts(ruleContexts) {
      return ruleContexts.map((ruleContext) =>
        ruleContext.replace("ais-", "custom-"),
      );
    },
  });
  ```
</ParamField>

### Full example

```js JavaScript icon=code theme={"system"}
// Create the render function
const renderQueryRuleContext = (renderOptions, isFirstRender) => {
  // We don't provide anything to render for this widget.
};

// Create the custom widget
const customQueryRuleContext = connectQueryRules(renderQueryRuleContext);

// Instantiate the custom widget
search.addWidgets([
  customQueryRuleContext({
    trackedFilters: {
      genre: () => ["Comedy", "Thriller"],
    },
  }),
]);
```
