Last active
September 1, 2017 09:14
-
-
Save hipertracker/2e02a069384a81aa7369 to your computer and use it in GitHub Desktop.
Example of using React context for ES6 classes
This file contains 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
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