Skip to content

Instantly share code, notes, and snippets.

@apackeer
Forked from ryanflorence/provideContext.js
Created August 4, 2016 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apackeer/d238df4545cff5a5e3e9a3f4c5a0e585 to your computer and use it in GitHub Desktop.
Save apackeer/d238df4545cff5a5e3e9a3f4c5a0e585 to your computer and use it in GitHub Desktop.
import React from 'react'
const provideContext = (contextKey, contextType) => (
React.createClass({
childContextTypes: {
[contextKey]: contextType
},
getChildContext() {
const { children, ...props } = this.props
return {
[contextKey]: props
}
},
render() {
return React.Children.only(this.props.children)
}
})
)
export default provideContext
import React from 'react'
export default (contextKey, contextType) => (
(Component) => (
React.createClass({
contextTypes: {
[contextKey]: contextType
},
render() {
const props = {
...this.props,
[contextKey]: this.context[contextKey]
}
return <Component {...props}/>
}
})
)
)
// usage
const Something = withContext('router', PropTypes.object)(React.createClass({
render() {
this.props.router
}
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment