Search code examples
javascriptreactjshandsontable

How to access multiple contexts in javascript function (React.Component class method)


I have React component, which renders 3th party HoC HotTable. HotTable have method afterValidate on it.

I am passing handleAfterValidate function to HotTable. The problem is that handleAfterValidate should have access to HotTable instance and at the same time access to HotTableWrapper instance (see code below).

By default this inside handleAfterValidate refers to HotTable instance. If I bind handler to React instance then I loose access to HotTable instance, but I need them both.

Is it possible to have access to both contexts in this case ?

class HotTableWrapper extends React.Component {
processCell(row, col) {
    // do something
}

handleAfterValidate(row, prop) {
    const col = this.propToCol(prop); // 'this' should refer to HotTable instance 
    this.processCell(row, col); // 'this' should refer to HotTableWrapper class instance
}

render() {
    return (
        <div>
            <HotTable afterValidate={this.handleAfterValidate} />
        </div>
    );
}

}


Solution

  • You can use currying function approach. If you have lodash on board, then you can do it like this:

    class HotTableWrapper extends React.Component {
        processCell(row, col) {
            // do something
        }
    
        handleAfterValidate(wrapper, row, prop) {
            const col = this.propToCol(prop); // 'this' should refer to HotTable instance 
            wrapper.processCell(row, col); // 'this' should refer to HotTableWrapper class instance
        }
    
        render() {
            return (
                <div>
                    <HotTable afterValidate={_.curry(this.handleAfterValidate)(this)} />
                </div>
            );
        }
    }
    

    https://lodash.com/docs/4.17.4#curry If you don't have lodash, just google it how to implement helper for currying.