webscopeio / react-textarea-autocomplete

📝 React component implements configurable GitHub's like textarea autocomplete.
MIT License
451 stars 80 forks source link

Does trigger support search from an array or api response? #230

Open gaohongwei opened 2 years ago

gaohongwei commented 2 years ago

Does trigger support search from an array or api response? The trigger now takes a predefined dictionary. trigger are keys of dictionary Can the trigger be current active word (or partial word), instead of the predefined chars or words?

dataProvider takes (token) as argument. What is the usage of it? How the value is passed to dataProvider? Any sample?

This is good package. But it is a little complicated to understand from the doc

sepulzera commented 2 years ago

The triggerChar is supposed to be a single character, that will fetch and build the autocomplete-list. On pressing the triggerChar, the dataProvider is called, and will get all following characters. The dataProvider could be a Promise, like an api-call, and the result is used to build the list.

Example:

export type AutocompleteListItem = {
  name: string;
  char: string;
}

export const fetchRecipeList = (searchTerm: string): Promise<Array<AutocompleteListItem>> => 
  request()
    .get(`${serverURLs.recipe}?search=${searchTerm}`)
    .then(res => res.body.results.map((recipe: RecipeDto) => ({ key: recipe.slug, name: recipe.slug, char: recipe.title } as AutocompleteListItem)))
    .catch(() => []);

interface IItemProps {
  entity: AutocompleteListItem;
}
const Item = ({ entity: { char } }: IItemProps) => <div>{char}</div>;

<ReactTextareaAutocomplete<AutocompleteListItem>
    /* ... */
    trigger={{
      ':': {
        dataProvider: token => fetchRecipeList(token),
        component: Item,
        output: item => item.char,
      },
    }} />

One can then type ':Beet' and the autocomplete-list will show all recipes for 'Beet'.

sepulzera commented 2 years ago

And just some clarification:

Can the trigger be current active word (or partial word), instead of the predefined chars or words?

This is probably undefined behaviour, but you could change the triggerChar dynamically. Just be aware that this package will treat the triggerChar as a single char, so changing the trigger char to a word could cause trouble for the dataProvider-function or whatelse.

Example:

<ReactTextareaAutocomplete<AutocompleteListItem>
    /* ... */
    trigger={{
      'apple': {
        dataProvider: token => fetchRecipeList(token),
        component: Item,
        output: item => item.char,
      },
    }} />

One can then type 'appleJ' and the fetchRecipeList-function would get passed 'ppleJ'. So... probably shouldn't do that.