1

When using the connect function in react-redux, a Higher Order Component is created. From an instance of that HOC, one can access the wrapped instance of the extended component. Is it possible, however, to retrieve the wrapped class from the HOC class?

E.g.:

class A extends React.Component {}

ConnectedA = connect(mapStateToProps, mapDispatch)(A);

ConnectedA.some_static_method_to_get_the_wrapped_class(); // === A

EDIT: For the sake of clarity, I do not have an instance of ConnectedA available. I need a static method or property. Does that exist?

CedricLaberge
  • 592
  • 2
  • 7
  • 22

1 Answers1

3

It's possible to use connected component getWrappedInstance method in conjunction with withRef option to get a ref of wrapped component:

this.aConnectedRef = React.createRef();

...

<ConnectedA ref={this.aConnectedRef} />

...

// after render
// this.aConnectedRef.current.getWrappedInstance() instanceof A === true

Wrapped class itself is available as WrappedComponent property:

ConnectedA.WrappedComponent === A

If A static method is needed then a reference to A class should be likely used directly, or it could be refactored to not require static method.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • 1
    As a general FYI, note that this option will probably be removed in React-Redux v6, and replaced with a `forwardRef` option that will allow you to more directly get a ref to the wrapped component instance. – markerikson Sep 13 '18 at 16:17