Skip to content

Instantly share code, notes, and snippets.

@felipeochoa
Created November 13, 2016 09:15
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 felipeochoa/453946fc8a75c32f2051366a145fcede to your computer and use it in GitHub Desktop.
Save felipeochoa/453946fc8a75c32f2051366a145fcede to your computer and use it in GitHub Desktop.
Testing the overriding of parent context in children
/**
* 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')
);
@felipeochoa
Copy link
Author

Also works when grandchild is owned by parent and not by child: https://jsfiddle.net/79e293az/2/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment