Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 649
Ben Carp Avatar asked Aug 13 '26 03:08

Ben Carp


1 Answers

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>;
like image 73
daliusd Avatar answered Aug 15 '26 21:08

daliusd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!