elastic / search-ui

Search UI. Libraries for the fast development of modern, engaging search experiences.
https://docs.elastic.co/search-ui
Apache License 2.0
1.92k stars 368 forks source link

Provide a typed key filter on the <WithSearch> component. #964

Closed davidhicks980 closed 1 year ago

davidhicks980 commented 1 year ago

Is your feature request related to a problem? Please describe. WithSearch is not strongly typed, and mapContextToProps is a bit verbose.

Describe the solution you'd like Provide a typed key filter on the component.

Describe alternatives you've considered

import { WithSearch } from "@elastic/react-search-ui";
import { SearchContextState } from "@elastic/search-ui";
// I'm using lodash to make the code clearer, but it's a simple function
import { pick } from "lodash-es";
import { ReactNode } from "react";

type Many<T> = T | ReadonlyArray<T>;

type SearchBuilderProps<U extends keyof SearchContextState> = {
  keys: Array<Many<U>>;
  children: (search: Pick<SearchContextState, U>) => ReactNode;
};

function SearchBuilder<T extends keyof SearchContextState>(
  props: SearchBuilderProps<T>
) {
  return (
    <WithSearch
      mapContextToProps={(search: SearchContextState) =>
        pick(search, ...props.keys)
      }>
      {search => props.children(search)}
    </WithSearch>
  );
}

export default SearchBuilder;

Usage:

const catFilter = () => <SearchBuilder keys={["clearFilters", "setFilter"]}>
    {(search) => (
      <button onClick={ e => search.setFilter("top_species", "cats") }>
           Cats
      </button>
    )}
</SearchBuilder>

Additional context Associated type hint:

image
botelastic[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Is this issue still important to you? If so, please leave a comment and let us know. As always, thank you for your contributions.