Skip to content

Instantly share code, notes, and snippets.

@johnsogg
Last active October 1, 2018 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnsogg/c0f55ef4952d5bad0d78d2dfb9809908 to your computer and use it in GitHub Desktop.
Save johnsogg/c0f55ef4952d5bad0d78d2dfb9809908 to your computer and use it in GitHub Desktop.
Material Design: How to maintain both type safety and styling with generic components
class DataTable<T> extends React.PureComponent<Props<T>, State> {
// nothing special about the implementation of DataTable. Just keep it
// unexported, because it will be exposed via the Wrapped thing below.
}
// If you have a component that takes type parameters and need to use 'withStyles', here is a
// way to maintain type safety:
//
// DataTable: Our custom component to wrap.
// T: Type parameter for DataTable
// styles: Function to apply themed CSS. signature is:
// (theme: Theme) => Record<"root" | "table", CSSProperties>
// WrappedDataTable: To placate TS compiler and use 'withStyles'. The secret is
// the 'C' member function, which is what the ['C'] is about.
export default class WrappedDataTable<T> extends React.PureComponent<
PropsOf<WrappedDataTable<T>['C']>,
State
> {
private readonly C = withStyles(styles)((props: DataTable<T>['props']) => (
<DataTable<T> {...props} />
));
render() {
return <this.C {...this.props} />;
}
}
@johnsogg
Copy link
Author

johnsogg commented Oct 1, 2018

This is just re-stating the original inspiration from mui/material-ui#11921 (comment)

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