Skip to content

Instantly share code, notes, and snippets.

@welteki
Created August 7, 2018 08:33
Show Gist options
  • Save welteki/8dae1a1e1dd89d26db311effabcf08bc to your computer and use it in GitHub Desktop.
Save welteki/8dae1a1e1dd89d26db311effabcf08bc to your computer and use it in GitHub Desktop.
Using HOC to create React component variants.
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