connectors connectToggle

Edit this page

Description

Toggle connector provides the logic to build a custom widget that will provide an on/off filtering feature based on an attribute value or values.

Two modes are implemented in the custom widget:

  • with or without the value filtered
  • switch between two values.

Usage

Usage
const search= instantsearch(/* parameters */);

const makeToggle= instantsearch.connectors.connectToggle(
function renderFn(
renderOpts: ToggleRenderingOptions,
isFirstRendering: boolean) {
// render the custom Toggle widget
} );

const customToggle = makeToggle(instanceOpts: CustomToggleWidgetOptions);
search.addWidget(customToggle);

Connector options

ToggleRenderingOptions

  • valueToggleValue

    The current toggle value.

  • createURL() => string

    Creates an URL for the next state.

  • refine(value) => undefined

    Updates to the next state by applying the toggle refinement.

  • widgetParamsObject

    All original CustomToggleWidgetOptions forwarded to the renderFn.

ToggleValue

  • namestring

    Human-readable name of the filter.

  • isRefinedboolean

    true if the toggle is on.

  • countnumber

    Number of results matched after applying the toggle refinement.

  • onFacetValueObject

    Value of the toggle when it’s on.

  • offFacetValueObject

    Value of the toggle when it’s off.

CustomToggleWidgetOptions

  • attributeNamestring

    Name of the attribute for faceting (eg. “free_shipping”).

  • labelstring

    Human-readable name of the filter (eg. “Free Shipping”).

  • values[Object]
    Default value: {on:true,off:undefined}

    Values to filter on when toggling.

Example

// custom `renderFn` to render the custom ClearAll widget
function renderFn(ToggleRenderingOptions, isFirstRendering) {
  ToggleRenderingOptions.widgetParams.containerNode
    .find('a')
    .off('click');

  var buttonHTML = `
    <a href="${ToggleRenderingOptions.createURL()}">
      <input
        type="checkbox"
        value="${ToggleRenderingOptions.value.name}"
        ${ToggleRenderingOptions.value.isRefined ? 'checked' : ''}
      />
      ${ToggleRenderingOptions.value.name} (${ToggleRenderingOptions.value.count})
    </a>
  `;

  ToggleRenderingOptions.widgetParams.containerNode.html(buttonHTML);
  ToggleRenderingOptions.widgetParams.containerNode
    .find('a')
    .on('click', function(event) {
      event.preventDefault();
      event.stopPropagation();

      ToggleRenderingOptions.refine(ToggleRenderingOptions.value);
    });
}

// connect `renderFn` to Toggle logic
var customToggle = instantsearch.connectors.connectToggle(renderFn);

// mount widget on the page
search.addWidget(
  customToggle({
    containerNode: $('#custom-toggle-container'),
    attributeName: 'free_shipping',
    label: 'Free Shipping (toggle single value)',
  })
);


Can't find what you are looking for? Open an issue, we'll get back to you.