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

# Federated two-column autocomplete

> Build a two-column autocomplete with recent searches, Query Suggestions, and product previews.

export const FlavorSwitcher = ({current, baseHref = "", options = [], label = "InstantSearch framework"}) => {
  if (options.length === 0) {
    return <div className="not-prose" role="alert" style={{
      margin: "0.25rem 0 1.5rem",
      padding: "0.75rem",
      border: "1px solid #f59e0b",
      borderRadius: "0.625rem",
      color: "inherit",
      fontSize: "0.875rem"
    }}>
        FlavorSwitcher requires at least one option.
      </div>;
  }
  const selected = options.find(option => option.value === current) ?? options[0];
  return <div className="not-prose mint-flavor-switcher">
      <style>{`
        .mint-flavor-switcher {
          --mfs-bg: #ffffff;
          --mfs-bg-hover: #f4f4f5;
          --mfs-bg-current: #eef2ff;
          --mfs-border: #d4d4d8;
          --mfs-fg: #18181b;
          --mfs-muted: #71717a;
          --mfs-accent: #4f46e5;
          position: relative;
          width: min(100%, 19rem);
          margin: 0.25rem 0 1.5rem;
          color: var(--mfs-fg);
          font-size: 0.875rem;
          line-height: 1.25rem;
        }

        .dark .mint-flavor-switcher {
          --mfs-bg: #18181b;
          --mfs-bg-hover: #27272a;
          --mfs-bg-current: #272747;
          --mfs-border: #3f3f46;
          --mfs-fg: #fafafa;
          --mfs-muted: #a1a1aa;
          --mfs-accent: #a5b4fc;
        }

        .mint-flavor-switcher details {
          position: relative;
        }

        .mint-flavor-switcher summary {
          display: flex;
          min-height: 2.75rem;
          box-sizing: border-box;
          align-items: center;
          justify-content: space-between;
          gap: 0.75rem;
          padding: 0.625rem 0.75rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          color: var(--mfs-fg);
          cursor: pointer;
          font-weight: 600;
          list-style: none;
          transition: border-color 150ms ease, box-shadow 150ms ease;
        }

        .mint-flavor-switcher summary::-webkit-details-marker {
          display: none;
        }

        .mint-flavor-switcher summary:hover {
          border-color: var(--mfs-accent);
        }

        .mint-flavor-switcher summary:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: 2px;
        }

        .mint-flavor-switcher__label {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .mint-flavor-switcher__chevron {
          flex: none;
          transition: transform 150ms ease;
        }

        .mint-flavor-switcher details[open] .mint-flavor-switcher__chevron {
          transform: rotate(180deg);
        }

        .mint-flavor-switcher__menu {
          position: absolute;
          z-index: 50;
          top: calc(100% + 0.375rem);
          left: 0;
          width: 100%;
          box-sizing: border-box;
          margin: 0;
          padding: 0.375rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          box-shadow: 0 12px 30px rgb(0 0 0 / 16%);
          list-style: none;
        }

        .mint-flavor-switcher__menu li {
          margin: 0;
          padding: 0;
        }

        .mint-flavor-switcher__option {
          display: grid;
          gap: 0.125rem;
          padding: 0.625rem 0.75rem;
          border-radius: 0.4rem;
          color: var(--mfs-fg);
          text-decoration: none;
        }

        .mint-flavor-switcher__option:hover {
          background: var(--mfs-bg-hover);
        }

        .mint-flavor-switcher__option:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: -2px;
        }

        .mint-flavor-switcher__option[aria-current="page"] {
          background: var(--mfs-bg-current);
          color: var(--mfs-accent);
        }

        .mint-flavor-switcher__name {
          font-weight: 600;
        }

        .mint-flavor-switcher__description {
          color: var(--mfs-muted);
          font-size: 0.8125rem;
        }

        @media (prefers-reduced-motion: reduce) {
          .mint-flavor-switcher summary,
          .mint-flavor-switcher__chevron {
            transition: none;
          }
        }
      `}</style>

      <details>
        <summary aria-label={`${label}: ${selected.label}`}>
          <span className="mint-flavor-switcher__label">{selected.label}</span>
          <svg className="mint-flavor-switcher__chevron" width="18" height="18" 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>
        </summary>

        <ul className="mint-flavor-switcher__menu" aria-label={label}>
          {options.map(option => {
    const isCurrent = option.value === selected.value;
    const href = option.href ?? `${baseHref.replace(/\/$/, "")}/${encodeURIComponent(option.value)}`;
    return <li key={option.value}>
                <a className="mint-flavor-switcher__option" href={href} aria-current={isCurrent ? "page" : undefined}>
                  <span className="mint-flavor-switcher__name">
                    {option.label}
                  </span>
                  {option.description ? <span className="mint-flavor-switcher__description">
                      {option.description}
                    </span> : null}
                </a>
              </li>;
  })}
        </ul>
      </details>
    </div>;
};

<div className="mint-flavor-switcher-slot not-prose">
  <FlavorSwitcher
    current="js"
    baseHref="/doc/guides/building-search-ui/ui-and-ux-patterns/autocomplete/examples/federated"
    options={[
{ value: "js", label: "JavaScript", description: "InstantSearch.js" },
{ value: "react", label: "React", description: "React InstantSearch" },
]}
  />
</div>

This example builds on the [`autocomplete`](/doc/guides/building-search-ui/ui-and-ux-patterns/autocomplete/js) widget guide.
It creates a federated autocomplete experience with recent searches and Query Suggestions on the left, and product previews on the right.

<Tabs>
  <Tab title="Desktop">
    <img src="https://mintcdn.com/algolia/nyJ2KZzw6bfBNB-S/images/autocomplete/widget-federated-desktop.png?fit=max&auto=format&n=nyJ2KZzw6bfBNB-S&q=85&s=df2d4d6d04ddbc1bbe73f4209b961eb2" alt="Federated autocomplete with recent searches and Query Suggestions on the left and product previews on the right (desktop)" width="1594" height="784" data-path="images/autocomplete/widget-federated-desktop.png" />
  </Tab>

  <Tab title="Mobile">
    <img src="https://mintcdn.com/algolia/nyJ2KZzw6bfBNB-S/images/autocomplete/widget-federated-mobile.png?fit=max&auto=format&n=nyJ2KZzw6bfBNB-S&q=85&s=66f7874dc3a81a2c863b22cbf05e7a33" alt="Federated autocomplete in detached mode on a narrow screen (mobile)" style={{ maxWidth: "280px" }} className="no-shadow" width="746" height="1190" data-path="images/autocomplete/widget-federated-mobile.png" />
  </Tab>
</Tabs>

<Columns>
  <Card title="Open CodeSandbox" icon="codesandbox" href="https://codesandbox.io/s/github/algolia/doc-code-samples/tree/master/instantsearch.js/autocomplete">
    Run and edit the federated autocomplete example in CodeSandbox.
  </Card>

  <Card title="Explore source code" icon="github" href="https://github.com/algolia/doc-code-samples/tree/master/instantsearch.js/autocomplete">
    Browse the source code for the federated autocomplete example on GitHub.
  </Card>
</Columns>

The example has three states. Each one arranges the same two columns differently:

| Search state    | Left column                                              | Right column                                                                                    |
| --------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| **Empty query** | Recent searches and popular searches                     | Quick access                                                                                    |
| **Results**     | Suggestions and [a category](#add-a-category-suggestion) | Product (and article) previews                                                                  |
| **No results**  | A "no results" message                                   | Popular categories. To show popular categories, add a source that returns category facet values |

The sections below build each piece, then combine them in a single `panel` template.

The `panel` template arranges the sources into two columns, and each source brings its own header and item templates:

```js JavaScript icon=code expandable theme={"system"}
import { liteClient as algoliasearch } from "algoliasearch/lite";
import instantsearch from "instantsearch.js";
import { autocomplete } from "instantsearch.js/es/widgets";

import "instantsearch.css/themes/satellite.css";

const searchClient = algoliasearch(
  "latency",
  "6be0576ff61c053d5f9a3225e2a90f76",
);

const search = instantsearch({
  indexName: "instant_search",
  searchClient,
});

search.addWidgets([
  autocomplete({
    container: "#autocomplete",
    placeholder: "Search for products",
    // Left column, top: recent searches from local storage
    showRecent: {
      templates: {
        header: (_, { html }) =>
          html`<span class="ais-AutocompleteIndexHeaderTitle"
            >Recent searches</span
          >`,
      },
    },
    // Left column, bottom: popular Query Suggestions
    showQuerySuggestions: {
      indexName: "instant_search_demo_query_suggestions",
      searchParameters: { hitsPerPage: 5 },
      templates: {
        header: (_, { html }) =>
          html`<span class="ais-AutocompleteIndexHeaderTitle">Suggestions</span>`,
      },
    },
    // Right column: product previews with image, name, price, and highlight
    indices: [
      {
        indexName: "instant_search",
        searchParameters: { hitsPerPage: 5 },
        templates: {
          header: ({ items }, { html }) =>
            items.length === 0
              ? null
              : html`<span class="ais-AutocompleteIndexHeaderTitle"
                  >Products</span
                >`,
          noResults: (_, { html }) =>
            html`<div class="demo-empty">No products found.</div>`,
          item: ({ item }, { html, components }) =>
            html`<div class="demo-product">
              <div class="demo-product-image">
                <img src="${item.image}" alt="${item.name}" />
              </div>
              <div>
                <p class="demo-product-name">
                  ${components.Highlight({ hit: item, attribute: "name" })}
                </p>
                <p class="demo-product-meta">${item.brand} · $${item.price}</p>
              </div>
            </div>`,
        },
      },
    ],
    // Access built-in sources by their element names and index sources by index name.
    templates: {
      panel: ({ elements }, { html }) =>
        html`<div class="demo-grid">
          <div class="demo-column">
            ${elements.recent} ${elements.suggestions}
          </div>
          <div class="demo-column">${elements["instant_search"]}</div>
        </div>`,
    },
  }),
]);

search.start();
```

Add CSS for the columns, product rows, and state-specific elements.
The [example style sheet](https://github.com/algolia/doc-code-samples/tree/master/instantsearch.js/autocomplete/src/app.css) includes classes for:

* Two-column grids
* Product rows
* Quick-access cards
* "See all" and no-results states

## Add a quick-access panel

You can show promotional cards or shortcuts when the query is empty.
Define them as static data and render them in the `panel` template.
When users type a query, show product previews instead:

```js JavaScript icon=code expandable theme={"system"}
// Quick-access cards shown in the empty state.
const QUICK_ACCESS = [
  {
    title: "Spring sale",
    subtitle: "up to 60% off",
    image: "https://picsum.photos/seed/spring-sale/300/200",
    href: "#",
  },
  {
    title: "New collection",
    subtitle: "spring / summer",
    image: "https://picsum.photos/seed/new-collection/300/200",
    href: "#",
  },
];

templates: {
  panel: ({ elements, indices }, { html }) => {
    const products = indices.find(
      (index) => index.indexName === "instant_search",
    );
    const isEmptyQuery = products?.results?.query === "";

    return html`<div class="demo-grid">
      <div class="demo-column">${elements.recent} ${elements.suggestions}</div>
      <div class="demo-column">
        ${isEmptyQuery && QUICK_ACCESS.length > 0
          ? html`<ul class="demo-quick">
              ${QUICK_ACCESS.map(
                (entry) => html`<li>
                  <a class="demo-quick-item" href="${entry.href}">
                    <img src="${entry.image}" alt="" />
                    <span class="demo-quick-title">${entry.title}</span>
                    <span class="demo-quick-subtitle">${entry.subtitle}</span>
                  </a>
                </li>`,
              )}
            </ul>`
          : elements["instant_search"]}
      </div>
    </div>`;
  },
},
```

<Note>
  For dynamic cards, return custom data from an [Algolia rule](/doc/guides/managing-results/rules/rules-overview).
  In the `panel` template, read the data from `results.userData` for the products index instead of using a static array.
</Note>

## Add a category suggestion

To show a category suggestion in the left column, find the products index and read the top product's `categories` from `results.hits[0]` in the `panel` template.
Guard against a missing or empty `categories` attribute, then render the category after the suggestions:

```js JavaScript icon=code theme={"system"}
const products = indices.find(
  (index) => index.indexName === "instant_search",
);
// Derive a category from the top product, if any.
const categories = products?.results?.hits?.[0]?.categories ?? [];

// In the left column, after the suggestions:
html`${elements.suggestions}
${categories.length > 0
  ? html`<div class="demo-category">${categories.join(" › ")}</div>`
  : null}`;
```

## Show a "See all" link

The index source has no `footer` template.
To show a **See all** link with the total number of matching results,
read the products index's `results.nbHits` in the `panel` template and render the link after the product previews:

```js JavaScript icon=code theme={"system"}
const products = indices.find(
  (index) => index.indexName === "instant_search",
);
const nbHits = products?.results?.nbHits ?? 0;

// In the right column, after the product elements:
html`${elements["instant_search"]}
${nbHits > 5
  ? html`<a class="demo-see-all" href="#">
      See all ${nbHits.toLocaleString()} results
    </a>`
  : null}`;
```

## Show the no-results state

When a result source has no items, the widget doesn't render its `item` template.
Use the source's `noResults` template to show a message such as "No products found", as shown in the main example.

## Combine the empty and typing states

The final `panel` template combines two states:

* For an empty query, show recent and popular searches in the left column and quick-access cards in the right column.
* After users enter a query, show Query Suggestions and a category in the left column and product previews in the right column.

To switch between the states:

* Remove the `header` template from `showQuerySuggestions`.
* Render the suggestions heading in the `panel` template. Use "Popular searches" for an empty query and "Suggestions" for a non-empty query.
* Show the heading only when the Query Suggestions source has results.

For the assembled `panel` template, see [`src/app.js`](https://github.com/algolia/doc-code-samples/tree/master/instantsearch.js/autocomplete/src/app.js).

## See also

* [Autocomplete](/doc/guides/building-search-ui/ui-and-ux-patterns/autocomplete/js) guide for the widget basics.
* [Rich text box with mentions](/doc/guides/building-search-ui/ui-and-ux-patterns/autocomplete/examples/mentions/js) for an example of a headless, connector-based pattern.
