Skip to content

Instantly share code, notes, and snippets.

@Voronar
Last active August 20, 2018 08:29
Show Gist options
  • Save Voronar/732bc3c121c3cb50dfcf0d3f13a71cb7 to your computer and use it in GitHub Desktop.
Save Voronar/732bc3c121c3cb50dfcf0d3f13a71cb7 to your computer and use it in GitHub Desktop.
React + TypeScript = ❤️
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export function withProps<InjectingProps extends {}>(injectingProps: InjectingProps) {
return function <ExtendedProps extends InjectingProps>(SourceComponent: React.ComponentType<ExtendedProps>) {
type WithPropsHocProps = Omit<ExtendedProps, keyof InjectingProps>;
class WithPropsHoc extends React.PureComponent<WithPropsHocProps> {
render() {
return (
<SourceComponent {...this.props} {...injectingProps}>
{this.props.children}
</SourceComponent>
);
}
}
return WithPropsHoc;
};
}
const Comp = withProps({
a: 1,
b: 2,
с: 'string',
})(
props => <div>{props.a + props.b + props.с}</div>,
);
<Comp />;
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export function withProps<ExtendedProps extends InjectingProps, InjectingProps>(injector: (props: Omit<ExtendedProps, keyof InjectingProps>) => InjectingProps) {
return function (SourceComponent: React.ComponentType<ExtendedProps>) {
type WithPropsHocProps = Omit<ExtendedProps, keyof InjectingProps>;
class WithPropsHoc extends React.PureComponent<WithPropsHocProps> {
render() {
return (
<SourceComponent {...this.props} {...injector(this.props)}>
{this.props.children}
</SourceComponent>
);
}
}
return WithPropsHoc;
};
}
const Comp = withProps(props => ({ id: props }))(
props => <div>{props.children}</div>,
);
<Comp />;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment