Skip to content

Instantly share code, notes, and snippets.

@hipertracker
Last active September 1, 2017 09:14
Show Gist options
  • Save hipertracker/2e02a069384a81aa7369 to your computer and use it in GitHub Desktop.
Save hipertracker/2e02a069384a81aa7369 to your computer and use it in GitHub Desktop.
Example of using React context for ES6 classes
import React, { PropTypes } from 'react';
@reactor
class Child extends React.Component {
componentDidMount() {
console.log('Child mounted with context reactor:', this.context.reactor);
}
render() {
return <span>Child Component</span>;
}
}
@injectReactor({
actions: ['action1', 'action2'],
store: ['store1']
})
class ChildContainer extends React.Component {
render() {
return <div>ChildContainer has <Child/></div>;
}
}
// // ES7 decorators require Babel stage=0
function reactor(Component) {
Component.contextTypes = {
reactor: PropTypes.object.isRequired
};
}
function injectReactor(opts) {
const createComponent = (Component, dataBindings) => {
return React.createClass({
childContextTypes: {
reactor: PropTypes.object
},
getChildContext() {
const {id} = this.props;
const reactor = {...dataBindings, id};
return {reactor};
},
componentDidMount() {
console.log(`${Component.name} mounted with props:`, this.props);
},
render() {
return <Component/>;
}
});
};
return target => createComponent(target, opts);
}
React.render(<ChildContainer id={1}/>, document.body);
/*
@see:
* https://github.com/JedWatson/react-context-example
* https://github.com/jordangarcia/nuclear-js-react-addons/blob/master/nuclearComponent.js
* https://medium.com/@learnreact/context-f932a9abab0e
* https://github.com/facebook/react/blob/v0.13.3/src/core/__tests__/ReactCompositeComponent-test.js#L548
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment