mayooran mayooran - 2 months ago 14
TypeScript Question

Accessing a method from another method in the same class which is passed as props to another class

I have the below methods in my Search.tsx class.

renderSuggestion(suggestion) {
<div className="buttons">
<button className="button">View Location</button>
<button className="button whitebutton" onClick={this.handleThatEvent.bind(this)}>Add to price checker</button>
</div>

}

render() {
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={this.getSuggestionValue}
renderSuggestion={this.renderSuggestion}
inputProps={inputProps}/>
}

public handleThatEvent(e){
//MOUSE CLICK LOGIC HERE
};


In here the method renderSuggestion is passed to AutoSuggest component. When a button in renderSuggestion is clicked I need to call the method handleThatEvent. But how can I access this method from renderSuggestion method? I tried assigning "that" in the constructor to "this" and tried to call the method that.handleThatEvent. But "that" returns undefined. How can I call this handleThatEvent in button click event of the renderSuggestion method? Any help would be much appreciated.

Answer

Just like you bound the handleThatEvent method, you should bind the renderSuggestion method:

<Autosuggest
    suggestions={suggestions}
    onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
    onSuggestionsClearRequested={this.onSuggestionsClearRequested}
    getSuggestionValue={this.getSuggestionValue}
    renderSuggestion={this.renderSuggestion.bind(this)}
    inputProps={inputProps}/>

But I'd advice you not to insert html from one component to another, the philosophy of react is that each component will manage its own state.
You should probably have the renderSuggestion method in the Autosuggest component and just pass it the handler function:

<Autosuggest
    suggestions={suggestions}
    onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
    onSuggestionsClearRequested={this.onSuggestionsClearRequested}
    getSuggestionValue={this.getSuggestionValue}
    onSuggestionButtonClick={this.handleThatEvent.bind(this)}
    inputProps={inputProps}/>
Comments