context-provider
v1.0.3
Published
Context provider for React.
Downloads
100
Maintainers
Readme
context-provider
Context provider for React. Inspired from fluxible-addons-react/provideContext
.
Install
$ npm install context-provider
Usage
with Babel
babel-preset-es2015
and babel-preset-react
, babel-plugin-transform-decorators-legacy
, babel-plugin-transform-class-properties
is required.
import provideContext from 'context-provider/lib/provideContext';
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
class Header extends Component {
static contextTypes = {
userName: PropTypes.string.isRequired
};
render() {
return (
<header>
<h1>Hello, {this.context.userName}.</h1>
</header>
);
}
}
@provideContext({
userName: PropTypes.string.isRequired
})
class App extends Component {
static contextTypes = {
userName: PropTypes.string.isRequired
};
render() {
return (
<div>
<Header />
<p>Hi! {this.context.userName}!</p>
</div>
);
}
}
ReactDOM.render(
<App context={{ userName: 'John Doe' }} />,
document.getElementById('app')
);
Legacy style
var provideContext = require('context-provider/lib/provideContext');
var React = require('react');
var ReactDOM = require('react-dom');
var Header = React.createClass({
contextTypes: {
userName: React.PropTypes.string.isRequired
},
render: function() {
return React.createElement(
'header',
null,
React.createElement(
'h1',
null,
'Hello, ',
this.context.userName,
'.'
)
);
}
});
var App = React.createClass({
contextTypes: {
userName: React.PropTypes.string.isRequired
},
render: function() {
return React.createElement(
'div',
null,
React.createElement(Header, null),
React.createElement(
'p',
null,
'Hi! ',
this.context.userName,
'!'
)
);
}
});
App = provideContext({
userName: React.PropTypes.string.isRequired
})(App);
ReactDOM.render(
React.createElement(App, {
context: { userName: 'John Doe' }
}),
document.getElementById('app')
);
License
MIT