Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 12-context.md #5923

Merged
merged 1 commit into from
Jan 29, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions docs/docs/12-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,38 @@ function Button(props, context) {
Button.contextTypes = {color: React.PropTypes.string};
```

## Updating context

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.

```javascript
var MediaQuery = React.createClass({
getInitialState: function(){
return {type:'desktop'};
},
childContextTypes: {
type: React.PropTypes.string
},
getChildContext: function() {
return {type: this.state.type};
},
componentDidMount: function(){
var checkMediaQuery = function(){
var type = window.matchMedia("min-width: 1025px").matches ? 'desktop' : 'mobile';
if (type !== this.state.type){
this.setState({type:type});
}
};

window.addEventListener('resize', checkMediaQuery);
checkMediaQuery();
},
render: function(){
return this.props.children;
}
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, we need a render function. You can keep it simple and just render something like <ComponentThatUsesContext />

```

## When not to use context

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.
Expand Down