Last active
October 1, 2018 17:04
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} />; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is just re-stating the original inspiration from mui/material-ui#11921 (comment)