CedricLaberge
CedricLaberge

Reputation: 662

Get wrapped component class from connected HOC in react-redux

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?

Upvotes: 1

Views: 2146

Answers (1)

Estus Flask
Estus Flask

Reputation: 222369

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.

Upvotes: 3

Related Questions