Search code examples
reactjscomponentsmixins

how to call a wrapper's method in react


I'm using a hoc to wrap a component. This hoc dispatches an action when unmounted. To do so, it calls a 'resetState' method. But what if I want to call that same resetState() at another place in the wrapped component. this.resetState does not work (logically), I only can imagine passing the function as a prop to the wrapper.

const resetAtUnmount = function (type) {
  // return the function to be called by redux 'connect'
  return function decorate(WrappedComponent) {
    // return the final class
    return class extends React.Component {
      resetState() {
        store.dispatch({ type });
      }

      componentWillUnmount() {
        this.resetState();
      }

      render() {
        return <WrappedComponent {...this.props} />;
      }
    };
  };
};

export default resetAtUnmount;


Solution

  • It sounds like you answered your own question. Pass resetState as a prop: <WrappedComponent {...this.props} resetState={this.resetState} />