Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
withProps HOC. For when you want to inject arbitrary stuff into a component
import * as React from 'react';
export default function withProps<InjectProps, Props = {}>(Component: React.ComponentType<Props & InjectProps>, props: InjectProps): React.ComponentClass<Pick<Props, Exclude<keyof Props, keyof InjectProps>>> {
return class extends React.Component<Props> {
static displayName = `withProps(${Component.displayName || Component.name})`;
static WrappedComponent = Component;
render() {
return <Component {...this.props} {...props} />
}
}
}
// test it out...
interface InjectedProps { a: number }
interface OwnProps { b: string }
const Test = (props: OwnProps & InjectedProps) => (<p>{props.a} {props.b}</p>)
let InjectedTest = withProps<InjectedProps, OwnProps>(Test, { a: 123 })
class Test2 extends React.Component {
render() {
return (
<>
<Test a={123} b="asd" />
<InjectedTest b="abc" />
</>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.