Skip to content

Commit 6aa1995

Browse files
committed
Add solution to motivation problem
1 parent 291b2fd commit 6aa1995

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

content/docs/context.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,13 @@ In a typical React application, data is passed top-down (parent to child) via pr
2121

2222
## Motivation
2323

24-
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.
24+
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:
2525

26-
`embed:context/motivation.js`
26+
`embed:context/motivation-problem.js`
27+
28+
Using context, we can avoid passing props through intermediate elements:
29+
30+
`embed:context/motivation-solution.js`
2731

2832
## API
2933

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const ColorContext = React.createContext();
2+
3+
class Button extends React.Component {
4+
render() {
5+
// highlight-range{2-8}
6+
return (
7+
<ColorContext.Consumer>
8+
{color => (
9+
<button style={{background: color}}>
10+
{this.props.children}
11+
</button>
12+
)}
13+
</ColorContext.Consumer>
14+
);
15+
}
16+
}
17+
18+
class Message extends React.Component {
19+
render() {
20+
return (
21+
<div>
22+
<p>{this.props.text}</p>
23+
<Button>Delete</Button>
24+
</div>
25+
);
26+
}
27+
}
28+
29+
class MessageList extends React.Component {
30+
render() {
31+
const color = 'purple';
32+
const children = this.props.messages.map(message => (
33+
<Message text={message.text} />
34+
));
35+
// highlight-range{2-4}
36+
return (
37+
<ColorContext.Provider value={color}>
38+
{children}
39+
</ColorContext.Provider>
40+
);
41+
}
42+
}

0 commit comments

Comments
 (0)