Created
November 13, 2016 09:15
-
-
Save felipeochoa/453946fc8a75c32f2051366a145fcede to your computer and use it in GitHub Desktop.
Testing the overriding of parent context in children
This file contains hidden or 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
/** | |
* Children can override parent's context, which means context is a form of dynamic scoping. | |
* Tested at: https://jsfiddle.net/79e293az/ | |
* https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js | |
* https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js | |
*/ | |
class Parent extends React.PureComponent { | |
getChildContext() { | |
return {name: this.props.appName}; | |
} | |
render() { | |
return ( | |
<div> | |
<h1>This app is called: {this.props.appName}</h1> | |
<Child></Child> | |
</div> | |
); | |
} | |
} | |
Parent.childContextTypes = {name: React.PropTypes.string}; | |
class Child extends React.PureComponent { | |
getChildContext() { | |
return {name: "Wrapped(" + this.context.name + ")"}; | |
} | |
render() { | |
const {name} = this.context; | |
return <div>Hello {name}<GrandChild/></div>; | |
} | |
} | |
Child.contextTypes = {name: React.PropTypes.string}; | |
Child.childContextTypes = {name: React.PropTypes.string}; | |
const GrandChild = (_, {name}) => <div>Grandchild: {name}</div> | |
GrandChild.contextTypes = {name: React.PropTypes.string}; | |
ReactDOM.render( | |
<Parent appName="test"/> | |
,document.getElementById('container') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also works when grandchild is owned by parent and not by child: https://jsfiddle.net/79e293az/2/