1

I am working on a project where I'm supposed to implement autocomplete functionality in a search box. I'm using React-InstantSearch and my SearchBox component is built up using an Algolia connector connectSearchBox. Now I want to implement autocomplete functionality in this same search box using connectAutoComplete. I'm confused how these two connectors should go together? Would really appreciate if you guys can help me on this. Thank you!

Link to Autocomplete connector: https://www.algolia.com/doc/api-reference/widgets/autocomplete/react/?client=jsx

Here's the relevant code:

SearchBox.jsx

export const SearchBoxBase = ({
  className,
  defaultRefinement,
  variant,
  headerTitle,
}) => {

....
....
....

  return (
    <div className={className}>
      {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
      <label id="search-input-box" className="fe__searchfield-input-box text-brand-primary">
        { headerTitle || searchText }
      </label>
      <SearchField.Advanced
        className={classNames('fe__searchfield', {
          'fe__searchfield--inverse': variant === STYLE_VARIANTS.inverse,
        })}
        value={defaultRefinement}
        onSubmit={handleSubmit}
        onClear={handleClear}
      >
        <SearchField.Input
          className="form-control-lg"
          aria-labelledby="search-input-box"
          data-nr-synth-id="catalog-search-input-field"
          data-hj-whitelist
        />
        <SearchField.ClearButton data-nr-synth-id="catalog-search-clear-button" />
        <SearchField.SubmitButton data-nr-synth-id="catalog-search-submit-button" />
      </SearchField.Advanced>
    </div>
  );
};


export default connectSearchBox(SearchBoxBase);

And this is what I'm planning to add into the SearchBox component:

const Autocomplete = ({ hits, currentRefinement, refine }) => (
  <ul>
    <li>
      <input
        type="search"
        value={currentRefinement}
        onChange={event => refine(event.currentTarget.value)}
      />
    </li>
    {hits.map(hit => (
      <li key={hit.objectID}>{hit.name}</li>
    ))}
  </ul>
);

const CustomAutocomplete = connectAutoComplete(Autocomplete);

The <input> tag in my case will be replaced by <SearchField.Input> in SearchBox.jsx

sameen
  • 11
  • 1

1 Answers1

0

The recommended approach is to switch your InstantSearch searchbox to be a virtual component and use the Autocomplete searchbox as your primary interface across all pages, including the search page.

Step-by-step guide is here: https://www.algolia.com/doc/ui-libraries/autocomplete/guides/using-instantsearch/

Chuck Meyer
  • 306
  • 1
  • 8