Skip to content Skip to sidebar Skip to footer

Passing Props To Higher-order Component

I have a higher-order component FormBuilder like this: const FormBuilder = (WrappedComponent) => { return class HOC extends React.Component { clearForm() { // ... } r

Solution 1:

You can act as following:

functionlogProps(InputComponent) {
  InputComponent.prototype.componentWillReceiveProps = function(nextProps) {
    console.log('Current props: ', this.props);
    console.log('Next props: ', nextProps);
  };
  // The fact that we're returning the original input is a hint that it has// been mutated.returnInputComponent;
}

// EnhancedComponent will log whenever props are receivedconstEnhancedComponent = logProps(InputComponent);

As parameter you can add the prop "submit" to pass in the method.

Ref: https://reactjs.org/docs/higher-order-components.html#dont-mutate-the-original-component-use-composition

Solution 2:

I think we might need a little more information about the structure of your project, but you could create a function within FormBuilder (funcA) that you pass down to the WrappedComponent that takes a function as an argument. Then when you click the button within WrappedComponent, it would send its own onSubmit function back up to funcA where it can be used within FormBuilder.

This can then be used on your other WrappedComponent (with the POST request) as you would just be sending the onSubmit function from both to be called within FormBuilder.

Hope this helps.

Solution 3:

I'm not at all sure if this would work, but maybe you could save the result of the form submission into the HOC's state, and then pass that information down to WrappedComponent via props. Then using getDerivedStateFromProps inside of WrappedComponent, you can pass the submitted form information into the component's submit function.

Post a Comment for "Passing Props To Higher-order Component"