Ben Carp
Ben Carp

Reputation: 26558

Using ConnectedComponentClass type React-Redux written in Typescript

I consider using a more strict type for my connected React-Redux component.

const ConnectedSelectionFilter = connect(mapsStateToProps, mapDispatchToProps)(SelectionFilter)

The generic type ConnectedComponentClass from React-Redux requires 2 type arguments

ConnectedComponentClass<C, P> = ComponentClass<JSX.LibraryManagedAttributes<C, P>, any> & {
    WrappedComponent: C;
}

C obviously refers to the wrapped component, but I'm not sure what does P refer to. I tried ComponentProps (though it can be extracted from the component type) and ownProps but it doesn't work.

How should I use this type generic? An example would be helpful.

Upvotes: 2

Views: 1043

Answers (1)

daliusd
daliusd

Reputation: 1165

Usually you don't need to use ConnectedComponentClass directly.

Common and correct way is to do following:

connect<StateProps, DispatchProps, OwnProps, State>(mapStateToProps)(ComponentHere);

StateProps is properties derived from Redux state.

Dispatch props can be only your dispatch function or more dispatch functions.

export interface DispatchProps {
    dispatch: Dispatch;
}

OwnProps - own properties of component.

State - your redux state.

ConnectedComponentClass might be useful if you import your components and need to create them dynamically, e.g. you want to keep different components sharing the same own properties in array and create them later based on your state.

ConnectedComponentClass<typeof Component, OwnProps>;

Upvotes: 2

Related Questions