Skip to content

Instantly share code, notes, and snippets.

@kevinkassimo
Created April 23, 2018 20:48
Show Gist options
  • Save kevinkassimo/74f5d6f119fd951e4b1bb28216b3cfbe to your computer and use it in GitHub Desktop.
Save kevinkassimo/74f5d6f119fd951e4b1bb28216b3cfbe to your computer and use it in GitHub Desktop.
const createDecorator = () => {
const {
Provider: RawProvider,
Consumer: RawConsumer,
} = React.createContext(null);
const provider = (value) => (WrappedClass) => {
return class extends React.Component {
constructor(props) {
super(props);
this.$update = (v) => {
this.setState({ $value: v });
};
this.state = {
$value: value,
$update: this.$update,
};
}
render() {
return (
<RawProvider value={this.state}>
<WrappedClass {...this.props} />
</RawProvider>
);
}
};
}
const consumer = (ctxName) => (WrappedClass) => {
if (!ctxName) {
ctxName = 'ctx';
}
const ctxUpdateName = `set${ ctxName.replace(/^\w/, (chr) => chr.toUpperCase()) }`;
return class extends React.Component {
render() {
const _consumerFunc = (context) => {
const _ctxProps = {
[ctxName]: context.$value,
[ctxUpdateName]: context.$update,
};
return <WrappedClass {...this.props} {..._ctxProps}/>
}
return (
<RawConsumer>
{_consumerFunc}
</RawConsumer>
);
}
};
}
return {
provider,
consumer,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment