Last active
October 27, 2018 15:37
-
-
Save ryanflorence/1e1290571337ebcea1c5a748e8f5b37d to your computer and use it in GitHub Desktop.
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 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 |
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 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 | |
} | |
})) |
There's a typo in SomeComponent.js
right? It should be importing from AppContext?
nope.
👏
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
This way components can only provide one context (no naming collisions, just shadowing) and a component can only ask for on context, and the entire context API is wrapped so the entire app is easily protected from future changes.