Clearing container when unmounting customized InstantSearch component

I’m trying to unmount a SortBy widget that I have customized, so I need to clear the widget’s container. How can I access the container that was passed into the widget on creation?

In the documentation, the container is just hard-coded into the unmount function:

function unmount() {
  $("#hits").remove();
}

However, I have multiple instances of these widgets and need to access the container from the unmount function. In the source, the unmount function is called with no arguments. Ideally, it would pass in the widget parameters including the container, so that it can be unmounted properly.

Is there any other way to do this?

I’ll forward to the relevant team to get more information as to why widgetParams are not passed to dispose.

You asked for an alternative way to do this, I believe you could do it via a wrapping factory, like so:

function makeHits(widgetParams) {
  const factory = instantsearch.connectors.connectHits(
    function renderHits({ hits }, isFirstRendering) {
      const container = widgetParams.container;
      $(container).html(hits.map(hit => JSON.stringify(hit)));
    },
    function unmount() {
      const container = widgetParams.container;
      $(container).remove();
    }
  );
  return factory(widgetParams);
}

search.addWidgets([
  makeHits({container: $('#hits-1')}),
  makeHits({container: $('#hits-2')})
]);

The widgetParams would hence become available to everything inside makeHits, including the unmount function. This creates one renderHits and one unmount function per invocation.

1 Like

Thank you, that will work for now.

FWIW it’s a known issue tracked on GitHub.

1 Like