webscopeio / react-textarea-autocomplete

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

TypeScript Example? #232

Open danieljaguiar opened 2 years ago

danieljaguiar commented 2 years ago

I am trying to implement this in TypeScript but have no luck so far...

Implementing Trigger Prop is very challenging (I am new to TS as well)

Has anyone implemented it?

sepulzera commented 2 years ago

Sorry for my late reply, you have probably already solved it by now. But in case anyone else is struggling either:

You can install the types, f. e. with npm:

npm install --save-dev @types/webscopeio__react-textarea-autocomplete

And instanciate the Component like usally:

  <ReactTextareaAutocomplete<AutocompleteListItem>
      name = 'foo'
      value = {fooValueString}
      onChange = {handleFooChange}
      rows = {8}
      loadingComponent = {Loading}
      movePopupAsYouType
      trigger={{
      ':': {
        dataProvider: token => fetchSomeList(token),
        component: Item,
        output: item => item.char,
      },
    }} />

And here some of the used objects and types. Note that some of the types probably should be provided by the @ŧypes-package, but I could not get used to it by much.

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

fetchSomeList: (searchTerm: string) => Promise<Array<AutocompleteListItem>>

interface IItemProps {
  entity: AutocompleteListItem;
}
const Item = ({ entity: { char } }: IItemProps) => <div>{char}</div>;
const Loading = () => <div className='loading'>Loading...</div>;
const handleFooChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {};

If you would rather like to look at a working example, you find one here (Disclaimer: my code): https://github.com/ownrecipes/ownrecipes-web/blob/development/src/recipe_form/components/IngredientGroupsBox.tsx#L262-L277

And the demo here: https://ownrecipes.github.io/ownrecipes-web/#/ownrecipes-web/recipe/edit/create

image