@samitouri / QOS-React-2 / commits / 6986fdd6bd

Update 12-context.md

Context was missing info on how to update the context after the initial render. Added a simple blurb and an example. [Docs] 12-context.md code review changes

Bobby committed Jan 26, 2016 at 13:25 UTC 6986fdd6bdbf64a37774caa7e38be97ead5af2b0
1 file changed +32
docs/docs/12-context.md
+32
@@ -160,6 +160,38 @@ function Button(props, context) {
160 Button.contextTypes = {color: React.PropTypes.string};
161 ```
162
163 +## Updating context
164 +
165 +The `getChildContext` function will be called when the state or props changes. In order to update data in the context, trigger a local state update with `this.setState`. This will trigger a new context and changes will be received by the children.
166 +
167 +```javascript
168 +var MediaQuery = React.createClass({
169 + getInitialState: function(){
170 + return {type:'desktop'};
171 + },
172 + childContextTypes: {
173 + type: React.PropTypes.string
174 + },
175 + getChildContext: function() {
176 + return {type: this.state.type};
177 + },
178 + componentDidMount: function(){
179 + var checkMediaQuery = function(){
180 + var type = window.matchMedia("min-width: 1025px").matches ? 'desktop' : 'mobile';
181 + if (type !== this.state.type){
182 + this.setState({type:type});
183 + }
184 + };
185 +
186 + window.addEventListener('resize', checkMediaQuery);
187 + checkMediaQuery();
188 + },
189 + render: function(){
190 + return this.props.children;
191 + }
192 +});
193 +```
194 +
195 ## When not to use context
196
197 Just as global variables are best avoided when writing clear code, you should avoid using context in most cases. In particular, think twice before using it to "save typing" and using it instead of passing explicit props.