Browse Source

Add solution to motivation problem

main
Alex Krolick 7 years ago
parent
commit
6aa199516d
  1. 8
      content/docs/context.md
  2. 0
      examples/context/motivation-problem.js
  3. 42
      examples/context/motivation-solution.js

8
content/docs/context.md

@ -21,9 +21,13 @@ In a typical React application, data is passed top-down (parent to child) via pr
## Motivation
Context is designed to relieve the pain of passing props down through a deeply nested component tree. For example, in the code below we manually thread through a color prop in order to style the Button and Message components. Using context, we can avoid passing props through intermediate elements.
Context is designed to relieve the pain of passing props down through a deeply nested component tree. For example, in the code below we manually thread through a color prop in order to style the Button and Message components:
`embed:context/motivation.js`
`embed:context/motivation-problem.js`
Using context, we can avoid passing props through intermediate elements:
`embed:context/motivation-solution.js`
## API

0
examples/context/motivation.js → examples/context/motivation-problem.js

42
examples/context/motivation-solution.js

@ -0,0 +1,42 @@
const ColorContext = React.createContext();
class Button extends React.Component {
render() {
// highlight-range{2-8}
return (
<ColorContext.Consumer>
{color => (
<button style={{background: color}}>
{this.props.children}
</button>
)}
</ColorContext.Consumer>
);
}
}
class Message extends React.Component {
render() {
return (
<div>
<p>{this.props.text}</p>
<Button>Delete</Button>
</div>
);
}
}
class MessageList extends React.Component {
render() {
const color = 'purple';
const children = this.props.messages.map(message => (
<Message text={message.text} />
));
// highlight-range{2-4}
return (
<ColorContext.Provider value={color}>
{children}
</ColorContext.Provider>
);
}
}
Loading…
Cancel
Save