Skip to content

Instantly share code, notes, and snippets.

@karlbright
Created May 25, 2015 06:39
Show Gist options
  • Save karlbright/cb33466401086c5dc2c3 to your computer and use it in GitHub Desktop.
Save karlbright/cb33466401086c5dc2c3 to your computer and use it in GitHub Desktop.
var React = require('react');
var assign = require('object-assign');
function createStubbedContextComponent(BaseComponent, context) {
var _contextTypes = {}, _context = context;
Object.keys(_context).forEach(function(key) {
_contextTypes[key] = React.PropTypes.any;
});
if(BaseComponent.contextTypes) {
assign(BaseComponent.contextTypes, _contextTypes);
} else {
assign(BaseComponent, { contextTypes: _contextTypes });
}
var StubbedContextComponent = React.createClass({
childContextTypes: _contextTypes,
getChildContext() { return _context; },
render() { return <BaseComponent {...this.state} {...this.props} />; }
});
return StubbedContextComponent;
}
module.exports = createStubbedContextComponent;
var React = require('react');
var createStubbedContextComponent = require('./createStubbedContextComponent');
var TestComponent = React.createClass({
render() { return <h1>{this.props.bar} {this.context.foo}</h1>; }
})
var StubbedComponent = createStubbedContextComponent(TestComponent, { foo: 'bar' })
require('domready')(function() {
React.render(
<StubbedComponent bar="foo" />,
document.getElementById('app')
);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment