From 6aa199516d515e95ad8191902e9b95f19cd7f28b Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Wed, 21 Mar 2018 10:04:11 -0700 Subject: [PATCH] Add solution to motivation problem --- content/docs/context.md | 8 +++- .../{motivation.js => motivation-problem.js} | 0 examples/context/motivation-solution.js | 42 +++++++++++++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) rename examples/context/{motivation.js => motivation-problem.js} (100%) create mode 100644 examples/context/motivation-solution.js diff --git a/content/docs/context.md b/content/docs/context.md index 1463720e..2b9ccfdd 100644 --- a/content/docs/context.md +++ b/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 diff --git a/examples/context/motivation.js b/examples/context/motivation-problem.js similarity index 100% rename from examples/context/motivation.js rename to examples/context/motivation-problem.js diff --git a/examples/context/motivation-solution.js b/examples/context/motivation-solution.js new file mode 100644 index 00000000..fbb6ac59 --- /dev/null +++ b/examples/context/motivation-solution.js @@ -0,0 +1,42 @@ +const ColorContext = React.createContext(); + +class Button extends React.Component { + render() { + // highlight-range{2-8} + return ( + + {color => ( + + )} + + ); + } +} + +class Message extends React.Component { + render() { + return ( +
+

{this.props.text}

+ +
+ ); + } +} + +class MessageList extends React.Component { + render() { + const color = 'purple'; + const children = this.props.messages.map(message => ( + + )); + // highlight-range{2-4} + return ( + + {children} + + ); + } +}