Last active
August 20, 2018 08:29
-
-
Save Voronar/732bc3c121c3cb50dfcf0d3f13a71cb7 to your computer and use it in GitHub Desktop.
React + TypeScript = ❤️
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
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 />; |
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
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