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

# queryRuleCustomData

> Shows custom data from applied index rules.

```ts Signature theme={"system"}
queryRuleCustomData({
  container: string | HTMLElement,
  // Optional parameters
  templates?: object,
  cssClasses?: object,
  transformItems?: function,
});
```

## Import

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

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

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

## About this widget

The `queryRuleCustomData` widget displays custom data from [index rules](/doc/guides/managing-results/rules/detecting-intent).

You can use this widget to display banners or recommendations returned by rules when they match search parameters.

## Examples

```js JavaScript icon=code theme={"system"}
queryRuleCustomData({
  container: "#queryRuleCustomData",
  templates: {
    default({ items }, { html }) {
      return html`
        ${items
          .map((item) => {
            const { title, banner, link } = item;

            if (!banner) {
              return;
            }

            return `
            <div>
              <h2>${title}</h2>
              <a href="${link}">
                <img src="${banner}" alt="${title}">
              </a>
            </div>
          `;
          })
          .join("")}
      `;
    },
  },
});
```

## Options

<ParamField body="container" type="string | HTMLElement" required>
  The CSS Selector or `HTMLElement` to insert the widget into.

  <CodeGroup>
    ```js string theme={"system"}
    queryRuleCustomData({
      container: "#queryRuleCustomData",
    });
    ```

    ```js HTMLElement theme={"system"}
    queryRuleCustomData({
      container: document.querySelector("#queryRuleCustomData"),
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="templates" type="object">
  The [templates](#templates) to use for the widget.

  ```js JavaScript icon=code theme={"system"}
  queryRuleCustomData({
    // ...
    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.

  ```js JavaScript icon=code theme={"system"}
  queryRuleCustomData({
    // ...
    cssClasses: {
      root: "MyCustomQueryRuleCustomData",
    },
  });
  ```
</ParamField>

<ParamField body="transformItems" type="function">
  A function that receives the list of items before they are displayed.
  It should return a new array with the same structure.
  Use this to transform, filter, or reorder the items.

  The function also has access to the full `results` data,
  including all standard [response parameters](/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/)
  and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
  such as `disjunctiveFacetsRefinements`.

  ```js JavaScript icon=code theme={"system"}
  queryRuleCustomData({
    // ...
    transformItems(items) {
      return items.filter((item) => typeof item.banner !== "undefined");
    },
  });

  // or, combined with results
  queryRuleCustomData({
    // ...
    transformItems(items, { results }) {
      return items.map((item) => ({
        ...item,
        visible: results.page === 0,
      }));
    },
  });
  ```
</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="default" type="function">
  The template to use for the custom data.
  It exposes the items returned by the rules.

  The following example assumes a rule returned this custom data.

  ```json JSON icon=braces theme={"system"}
  {
    "title": "This is an image",
    "banner": "image.png",
    "link": "https://website.com/"
  }
  ```

  <CodeGroup>
    ```js function theme={"system"}
    queryRuleCustomData({
      // ...
      templates: {
        default({ items }, { html }) {
          return html`
            ${items
              .map((item) => {
                const { title, banner, link } = item;

                if (!banner) {
                  return null;
                }

                return `
                <div>
                  <h2>${title}</h2>
                  <a href="${link}">
                    <img src="${banner}" alt="${title}">
                  </a>
                </div>
              `;
              })
              .join("")}
          `;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    queryRuleCustomData({
      // ...
      templates: {
        default: `
          {{#items}}
            {{#banner}}
              <div>
                <h2>{{title}}</h2>
                <a href="{{link}}">
                  <img src="{{banner}}" alt="{{title}}">
                </a>
              </div>
            {{/banner}}
          {{/items}}
        `,
      },
    });
    ```
  </CodeGroup>
</ParamField>

## HTML output

```html HTML icon=code-xml theme={"system"}
<div class="ais-QueryRuleCustomData"></div>
```

## Customize the UI with `connectQueryRules`

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

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

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

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

  ```js Import with a 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 renderQueryRuleCustomData = (renderOptions, isFirstRender) => {
  // Rendering logic
};

// 2. Create the custom widget
const customQueryRuleCustomData = connectQueryRules(renderQueryRuleCustomData);

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

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

  // Render the widget
};
```

#### Render options

<ParamField body="items" type="object[]">
  The items that matched the Rule.

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

    document.querySelector("#queryRuleCustomData").innerHTML = `
      <ul>
        ${items.map((item) => `<li>${item.title}</li>`).join("")}
      </ul>
    `;
  };
  ```
</ParamField>

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

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

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

  // ...

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

search.addWidgets([
  customQueryRuleCustomData({
    // Optional parameters
    transformItems,
  }),
]);
```

#### Instance options

<ParamField body="transformItems" type="function">
  A function that receives the list of items before they are displayed.
  It should return a new array with the same structure.
  Use this to transform, filter, or reorder the items.

  The function also has access to the full `results` data,
  including all standard [response parameters](/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/)
  and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
  such as `disjunctiveFacetsRefinements`.

  ```js JavaScript icon=code theme={"system"}
  customQueryRuleCustomData({
    transformItems(items) {
      return items.filter((item) => typeof item.banner !== "undefined");
    },
  });

  // or, combined with results
  customQueryRuleCustomData({
    transformItems(items, { results }) {
      return items.map((item) => ({
        ...item,
        visible: results.page === 0,
      }));
    },
  });
  ```
</ParamField>

### Full example

<CodeGroup>
  ```html HTML theme={"system"}
  <div id="queryRuleCustomData"></div>
  ```

  ```js JavaScript theme={"system"}
  // Create the render function
  const renderQueryRuleCustomData = (renderOptions, isFirstRender) => {
    const { items, widgetParams } = renderOptions;

    if (isFirstRender) {
      return;
    }

    widgetParams.container.innerHTML = `
      <ul>
        ${items.map((item) => `<li>${item.title}</li>`).join("")}
      </ul>
    `;
  };

  // Create the custom widget
  const customQueryRuleCustomData = connectQueryRules(renderQueryRuleCustomData);

  // Instantiate the custom widget
  search.addWidgets([
    customQueryRuleCustomData({
      container: document.querySelector("#queryRuleCustomData"),
    }),
  ]);
  ```
</CodeGroup>
