Skip to content

Instantly share code, notes, and snippets.

@MagsMagnoli
Last active March 14, 2020 01:20
Show Gist options
  • Save MagsMagnoli/7645260cf5bb206c31259c32e985e3d8 to your computer and use it in GitHub Desktop.
Save MagsMagnoli/7645260cf5bb206c31259c32e985e3d8 to your computer and use it in GitHub Desktop.
How to export a generic connected react component

React Generic Connected Component

The standard export default connect(...)(Component) method does not work if you with for Component to be generic

You must instead wrap the call to connect in a function as so:

export default function connectedComponent<T>() {
  return connect<StateProps, DispatchProps>(
    mapStateToProps,
    mapDispatchToProps
  )(Component as new (props: ComponentProps<T>) => Component<T>);
}

Consumers must invoke the function with the generic before using them in code:

import ConnectedComponent from './ConnectedComponent'

const TypedConnectedComponent = ConnectedComponent<Type>();

...

<TypedConnectedComponent
  ...
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment