From bd06bbc1a7fd6e8bf4d09c33c1188d78f9ec5a2a Mon Sep 17 00:00:00 2001 From: Brian Vaughn Date: Sat, 24 Mar 2018 09:30:27 -0700 Subject: [PATCH] Added context HOC example to reference --- content/docs/context.md | 20 ++++++++++++++++++- .../context/higher-order-component-before.js | 10 ++++++++++ .../context/higher-order-component-usage.js | 7 +++++++ examples/context/higher-order-component.js | 18 +++++++++++++++++ 4 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 examples/context/higher-order-component-before.js create mode 100644 examples/context/higher-order-component-usage.js create mode 100644 examples/context/higher-order-component.js diff --git a/content/docs/context.md b/content/docs/context.md index e98dffad..2e54d512 100644 --- a/content/docs/context.md +++ b/content/docs/context.md @@ -14,10 +14,10 @@ In a typical React application, data is passed top-down (parent to child) via pr - [Provider](#provider) - [Consumer](#consumer) - [Examples](#examples) - - [Static Context](#static-context) - [Dynamic Context](#dynamic-context) - [Consuming Multiple Contexts](#consuming-multiple-contexts) - [Accessing Context in Lifecycle Methods](#accessing-context-in-lifecycle-methods) + - [Consuming Context with a HOC](#consuming-context-with-a-hoc) - [Forwarding Refs to Context Consumers](#forwarding-refs-to-context-consumers) - [Caveats](#caveats) - [Legacy API](#legacy-api) @@ -104,6 +104,24 @@ Accessing values from context in lifecycle methods is a relatively common use ca `embed:context/lifecycles.js` +### Consuming Context with a HOC + +Some types of contexts are consumed by many components (e.g. theme or localization). It can be tedious to explicitly wrap each dependency with a `` element. A [higher-order component](/docs/higher-order-components.html) can help with this. + +For example, a button component might consume a theme context like so: + +`embed:context/higher-order-component-before.js` + +That's alright for a few components, but what if we wanted to use the theme context in a lot of places? + +We could create a higher-order component called `withTheme`: + +`embed:context/higher-order-component.js` + +Now any component that depends on the theme context can easy subscribe to it using the `withTheme` function we've created: + +`embed:context/higher-order-component-usage.js` + ### Forwarding Refs to Context Consumers One issue with the render prop API is that refs don't automatically get passed to wrapped elements. To get around this, use `React.forwardRef`: diff --git a/examples/context/higher-order-component-before.js b/examples/context/higher-order-component-before.js new file mode 100644 index 00000000..eaeb7249 --- /dev/null +++ b/examples/context/higher-order-component-before.js @@ -0,0 +1,10 @@ +const ThemeContext = React.createContext('light'); + +function ThemedButton(props) { + // highlight-range{2-4} + return ( + + {theme =>