const children = this.props.messages.map((message) =>
<Messagetext={message.text}color={color}/>
);
return <div>{this.props.children}</div>;
}
});
}
```
In this example, we manually thread through a `color` prop in order to style the `Button` and `Message` components appropriately. Theming is a good example of when you might want an entire subtree to have access to some piece of information (a color). Using context, we can pass this through the tree automatically:
var children = this.props.messages.map(function(message) {
return <Messagetext={message.text}/>;
});
}
render() {
const children = this.props.messages.map((message) =>
<Messagetext={message.text}/>
);
return <div>{children}</div>;
}
});
}
MessageList.childContextTypes = {
color: React.PropTypes.string
};
```
By adding `childContextTypes` and `getChildContext` to `MessageList` (the context provider), React passes the information down automatically and any component in the subtree (in this case, `Button`) can access it by defining `contextTypes`.
If `contextTypes` is not defined, then `this.context` will be an empty object.
If `contextTypes` is not defined, then `context` will be an empty object.
## Parent-child coupling
@ -150,13 +153,11 @@ void componentDidUpdate(
Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows the `Button` component above written as a stateless functional component.
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() {
class MediaQuery extends React.Component {
constructor(props) {
super(props);
this.state = {type:'desktop'};
}
getChildContext() {
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});
}
componentDidMount() {
const checkMediaQuery = () => {
const type = window.matchMedia("(min-width: 1025px)").matches ? 'desktop' : 'mobile';