Skip to content Skip to sidebar Skip to footer

Access Wrapped Component Function From HOC

Imagine a HOC for touch behavior that detects key touch events through onTouchStart. Now the wrapped components using the touch HOC, will have its own handler logic. How can my HOC

Solution 1:

Whenever possible, I would try not to pull logic back up the tree, but rather pass more down.

There are probably many ways to achieve this, but one option I see in this case is to change the prop provided to the wrapped component to be a function that constructs the handler for them with the provided custom logic.

TouchBehavior HOC

const TouchBehavior = (WrappedComponent) =>

    class extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                active: false,
            };
            this.handleAction = this.handleAction.bind(this);
            this.setActiveState = this.setActiveState.bind(this);
            this.resetActiveState = this.resetActiveState.bind(this);
        }

        handleAction(e, customHandler) {
            e.preventDefault();
            this.setActiveState();
            customHandler();
            _.delay(() => this.resetActiveState() , 150);
        }

        setActiveState() {
            this.setState ({
                active: true
            });
        }

        resetActiveState() {
            this.setState ({
                active: false
            });
        }

        render() {
            let touchBehaviorProps = (customHandler) => ({
                onTouchStart: (e) => this.handleAction(e, customHandler)
            });
            return <WrappedComponent {...this.props} touchBehaviorProps={touchBehaviorProps} />
        }
    };

Wrapped Component

class Button extends React.Component {

 componentSpecificHandlerLogic(){
  //logic goes here
 }

 render () {
  return <button {...this.props.touchBehaviorProps(componentSpecificHandlerLogic)}></button>
 }
}

Post a Comment for "Access Wrapped Component Function From HOC"