Have a method call another method within a function component

208 views Asked by At

I am using a component called DocumentPicker from the Fluent UI library.

This components has several methods:

<DocumentPicker
    removeButtonAriaLabel="Remove"
    onRenderSuggestionsItem={SuggestedBigItem as any}
    onResolveSuggestions={ /* do some stuff here */ }
    onRenderItem={SelectedDocumentItem}
    getTextFromItem={getTextFromItem}
    pickerSuggestionsProps={pickerSuggestionsProps}
    disabled={isPickerDisabled}
    inputProps={inputProps}
  />

For my specific scenario, I'd like to have a method of this component call another method. For example, have onEmptyInputFocus trigger onResolveSuggestions. How can I accomplish this?

[edit] Basically I am trying to accomplish with a function component what I would be able to do using "this" on a class component. In my class component I could write something like:

  public onEmptyInputFocus () {this.onResolveSuggestions();}
2

There are 2 answers

3
Tasos On

Since you specify these methods, it's pretty easy:

const _onEmptyInputFocus = () => {
  onResolveSuggestions()
}

<DocumentPicker
    removeButtonAriaLabel="Remove"
    onEmptyInputFocus={_onEmptyInputFocus}
    onRenderSuggestionsItem={SuggestedBigItem as any}
    onResolveSuggestions={onFilterChanged}
    onRenderItem={SelectedDocumentItem}
    getTextFromItem={getTextFromItem}
    pickerSuggestionsProps={pickerSuggestionsProps}
    disabled={isPickerDisabled}
    inputProps={inputProps}
  />
0
Christophe On

I think I am pretty clear now that it cannot be accomplished with function components. You would have to know the internals of the component and tweak it.

A workaround is to use a ref and work with the underlying HTML element. In Fluent UI the prop is actually called componentRef, not just ref.