Created
August 7, 2018 08:33
-
-
Save welteki/8dae1a1e1dd89d26db311effabcf08bc to your computer and use it in GitHub Desktop.
Using HOC to create React component variants.
This file contains 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
import * as React from 'react'; | |
import { omit } from 'lodash'; | |
export const withVariants = <O extends {}, T extends {}>( | |
Component: React.ComponentClass<O> | React.StatelessComponent<O>, | |
variants: T | |
) => { | |
type Variants = keyof T; | |
interface ExtenralProps { | |
variant?: Variants; | |
} | |
return class extends React.Component<O & ExtenralProps> { | |
render() { | |
// const { variant, ...passThroughProps } = this.props; | |
// Hack: use lodash instead of object rest destructuring operator to avoid problems with types | |
const { variant } = this.props; | |
const passThroughProps = omit(this.props, ['variant']); | |
const variantProps = variants[variant]; | |
const props = Object.assign({}, variantProps, passThroughProps); | |
return <Component {...props} />; | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment