Browse Source

Merge pull request #4 from alexkrolick/context-tweaks

Context tweaks
main
Brian Vaughn 7 years ago
committed by GitHub
parent
commit
3af89c9c1a
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 38
      content/docs/context.md
  2. 14
      content/docs/legacy-context.md
  3. 12
      examples/context/forwarding-refs.js
  4. 22
      examples/context/lifecycles.js
  5. 47
      examples/context/motivation-problem.js
  6. 60
      examples/context/motivation-solution.js
  7. 38
      examples/context/multiple-contexts.js
  8. 28
      examples/context/theme-detailed-app.js
  9. 2
      examples/context/theme-detailed-theme-context.js
  10. 55
      examples/context/theme-example.js

38
content/docs/context.md

@ -8,7 +8,7 @@ Context provides a way to pass data through the component tree without having to
In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like this between components without having to explicitly pass a prop through every level of the tree. In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like this between components without having to explicitly pass a prop through every level of the tree.
- [Motivation](#motivation) - [When to Use Context](#when-to-use-context)
- [API](#api) - [API](#api)
- [React.createContext](#reactcreatecontext) - [React.createContext](#reactcreatecontext)
- [Provider](#provider) - [Provider](#provider)
@ -16,12 +16,15 @@ In a typical React application, data is passed top-down (parent to child) via pr
- [Examples](#examples) - [Examples](#examples)
- [Static Context](#static-context) - [Static Context](#static-context)
- [Dynamic Context](#dynamic-context) - [Dynamic Context](#dynamic-context)
- [Consuming Multiple Contexts](#consuming-multiple-contexts)
- [Accessing Context in Lifecycle Methods](#accessing-context-in-lifecycle-methods)
- [Forwarding Refs to Context Consumers](#forwarding-refs-to-context-consumers)
- [Legacy API](#legacy-api) - [Legacy API](#legacy-api)
## Motivation ## When to Use Context
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: Context is designed to share data that can be considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a "theme" prop in order to style the Button component:
`embed:context/motivation-problem.js` `embed:context/motivation-problem.js`
@ -29,6 +32,8 @@ Using context, we can avoid passing props through intermediate elements:
`embed:context/motivation-solution.js` `embed:context/motivation-solution.js`
Note: Don't use context just to avoid passing props a few levels down. Stick to cases where the same data needs to accessed in many components at multiple levels.
## API ## API
### `React.createContext` ### `React.createContext`
@ -55,13 +60,13 @@ Accepts a `value` prop to be passed to Consumers that are descendants of this Pr
```js ```js
<Consumer> <Consumer>
{ value => { /* render something based on the context value */ } } {value => /* render something based on the context value */}
</Consumer> </Consumer>
``` ```
A React component that subscribes to context changes. A React component that subscribes to context changes.
Requires a [function as a child](/docs/render-props.html#using-props-other-than-render). This function receives the current context value and returns a React node. It will be called whenever the Provider's value is updated. Requires a [function as a child](/docs/render-props.html#using-props-other-than-render). The function receives the current context value and returns a React node. All consumers are re-rendered whenever the Provider value changes. Changes are determined by comparing the new and old values using [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
> Note: > Note:
> >
@ -69,12 +74,6 @@ Requires a [function as a child](/docs/render-props.html#using-props-other-than-
## Examples ## Examples
### Static Context
Here is an example illustrating how you might inject a "theme" using context:
`embed:context/theme-example.js`
### Dynamic Context ### Dynamic Context
A more complex example with dynamic values for the theme: A more complex example with dynamic values for the theme:
@ -88,8 +87,21 @@ A more complex example with dynamic values for the theme:
**app.js** **app.js**
`embed:context/theme-detailed-app.js` `embed:context/theme-detailed-app.js`
## Consuming Multiple Contexts
`embed:context/multiple-contexts.js`
## Accessing Context in Lifecycle Methods
`embed:context/lifecycles.js`
## Forwarding Refs to Context Consumers
`embed:context/forwarding-refs.js`
## Legacy API ## Legacy API
> The legacy context API was deprecated in React 16.3 and will be removed in version 17. > Note:
> >
> React previously shipped with an experimental context API. The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. Read the [legacy context docs here](/docs/legacy-context.html). > React previously shipped with an experimental context API. The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. The legacy API will be removed in React 17. Read the [legacy context docs here](/docs/legacy-context.html).

14
content/docs/legacy-context.md

@ -4,15 +4,15 @@ title: Legacy Context
permalink: docs/legacy-context.html permalink: docs/legacy-context.html
--- ---
> Deprecation Warning > Note:
> >
> The legacy API has been deprecated and will be removed in version 17. > The legacy context API will be removed in version 17.
> Use the [new context API](/docs/context.html) introduced with version 16.3. > Use the [new context API](/docs/context.html) introduced with version 16.3.
> The legacy API will continue working for all 16.x releases. > The legacy API will continue working for all 16.x releases.
## How To Use Context ## How To Use Context
> This section documents a deprecated API. See the [new API](/docs/context.html). > This section documents a legacy API. See the [new API](/docs/context.html).
Suppose you have a structure like: Suppose you have a structure like:
@ -107,7 +107,7 @@ If `contextTypes` is not defined, then `context` will be an empty object.
### Parent-Child Coupling ### Parent-Child Coupling
> This section documents a deprecated API. See the [new API](/docs/context.html). > This section documents a legacy API. See the [new API](/docs/context.html).
Context can also let you build an API where parents and children communicate. For example, one library that works this way is [React Router V4](https://reacttraining.com/react-router): Context can also let you build an API where parents and children communicate. For example, one library that works this way is [React Router V4](https://reacttraining.com/react-router):
@ -139,7 +139,7 @@ Before you build components with an API similar to this, consider if there are c
### Referencing Context in Lifecycle Methods ### Referencing Context in Lifecycle Methods
> This section documents a deprecated API. See the [new API](/docs/context.html). > This section documents a legacy API. See the [new API](/docs/context.html).
If `contextTypes` is defined within a component, the following [lifecycle methods](/docs/react-component.html#the-component-lifecycle) will receive an additional parameter, the `context` object: If `contextTypes` is defined within a component, the following [lifecycle methods](/docs/react-component.html#the-component-lifecycle) will receive an additional parameter, the `context` object:
@ -154,7 +154,7 @@ If `contextTypes` is defined within a component, the following [lifecycle method
### Referencing Context in Stateless Functional Components ### Referencing Context in Stateless Functional Components
> This section documents a deprecated API. See the [new API](/docs/context.html). > This section documents a legacy API. See the [new API](/docs/context.html).
Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows a `Button` component written as a stateless functional component. Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows a `Button` component written as a stateless functional component.
@ -171,7 +171,7 @@ Button.contextTypes = {color: PropTypes.string};
### Updating Context ### Updating Context
> This section documents a deprecated API. See the [new API](/docs/context.html). > This section documents a legacy API. See the [new API](/docs/context.html).
Don't do it. Don't do it.

12
examples/context/forwarding-refs.js

@ -0,0 +1,12 @@
const Button = ({theme, children}) => (
<button className={theme ? 'dark' : 'light'}>
{children}
</button>
);
// highlight-range{1,3}
export default React.forwardRef((props, ref) => (
<ThemeContext.Consumer>
{theme => <Button {...props} theme={theme} ref={ref} />}
</ThemeContext.Consumer>
));

22
examples/context/lifecycles.js

@ -0,0 +1,22 @@
class Button extends React.Component {
componentDidMount() {
// highlight-next-line
alert(this.props.theme);
}
render() {
const {theme, children} = this.props;
return (
<button className={theme ? 'dark' : 'light'}>
{children}
</button>
);
}
}
// highlight-range{3}
export default props => (
<ThemeContext.Consumer>
{theme => <Button {...props} theme={theme} />}
</ThemeContext.Consumer>
);

47
examples/context/motivation-problem.js

@ -1,34 +1,23 @@
class Button extends React.Component { const ThemedButton = props => {
render() { //highlight-range{1}
return ( return <Button theme={props.theme} />;
<button style={{background: this.props.color}}> };
{this.props.children}
</button>
);
}
}
class Message extends React.Component { // An intermediate component
render() { const Toolbar = props => {
// highlight-range{1-3} // highlight-range{1-2,5}
// The Message component must take `color` as as prop to pass it // The Toolbar component must take an extra theme prop
// to the Button. Using context, the Button could connect to the // and pass it to the ThemedButton
// color context on its own. return (
return ( <div>
<div> <ThemedButton theme={props.theme} />
<p>{this.props.text}</p> </div>
<Button color={this.props.color}>Delete</Button> );
</div> };
);
}
}
class MessageList extends React.Component { class App extends React.Component {
render() { render() {
const color = 'purple'; // highlight-range{1}
const children = this.props.messages.map(message => ( return <Toolbar theme="dark" />;
<Message text={message.text} color={color} />
));
return <div>{children}</div>;
} }
} }

60
examples/context/motivation-solution.js

@ -1,43 +1,33 @@
// highlight-range{1} // Create a theme context, defaulting to light theme
const ColorContext = React.createContext(); // highlight-next-line
const ThemeContext = React.createContext('light');
class Button extends React.Component { const ThemedButton = props => {
render() { // highlight-range{1,3-5}
// highlight-range{2-8} // The ThemedButton receives the theme from context
return ( return (
<ColorContext.Consumer> <ThemeContext.Consumer>
{color => ( {theme => <Button theme={theme} />}
<button style={{background: color}}> </ThemeContext.Consumer>
{this.props.children} );
</button> };
)}
</ColorContext.Consumer>
);
}
}
class Message extends React.Component { // An intermediate component
render() { const Toolbar = props => {
return ( return (
<div> <div>
<p>{this.props.text}</p> <ThemedButton />
<Button>Delete</Button> </div>
</div> );
); };
}
}
class MessageList extends React.Component { class App extends React.Component {
render() { render() {
const color = 'purple'; // highlight-range{2,4}
const children = this.props.messages.map(message => (
<Message text={message.text} />
));
// highlight-range{2-4}
return ( return (
<ColorContext.Provider value={color}> <ThemeContext.Provider value="dark">
{children} <Toolbar />
</ColorContext.Provider> </ThemeContext.Provider>
); );
} }
} }

38
examples/context/multiple-contexts.js

@ -0,0 +1,38 @@
// Theme context, default to light theme
// highlight-next-line
const ThemeContext = React.createContext('light');
// Signed-in user context
// highlight-next-line
const UserContext = React.createContext();
class App extends React.Component {
static propTypes = {
theme: PropTypes.string,
signedInUser: PropTypes.shape({
id: number,
name: string,
avatar: string,
}),
};
render() {
// highlight-range{9}
return (
<ThemeContext.Provider value={this.props.theme}>
<UserContext.Provider
value={this.props.signedInUser}>
<ThemeContext.Consumer>
{theme => (
<UserContext.Consumer>
{user => (
<ProfilePage user={user} theme={theme} />
)}
</UserContext.Consumer>
)}
</ThemeContext.Consumer>
</UserContext.Provider>
</ThemeContext.Provider>
);
}
}

28
examples/context/theme-detailed-app.js

@ -1,6 +1,15 @@
import {ThemeContext, themes} from './theme-context'; import {ThemeContext, themes} from './theme-context';
import ThemedButton from './button'; import ThemedButton from './button';
// An intermediate component that uses the ThemedButton
const Toolbar = props => {
return (
<ThemedButton onClick={props.changeTheme}>
Change Theme
</ThemedButton>
);
};
class App extends React.Component { class App extends React.Component {
state = { state = {
theme: themes.light, theme: themes.light,
@ -16,13 +25,20 @@ class App extends React.Component {
}; };
render() { render() {
//highlight-range{2,6} //highlight-range{1-3}
// The ThemedButton button inside the ThemeProvider
// uses the theme from state while the one outside uses
// the default dark theme
//highlight-range{3-5,7}
return ( return (
<ThemeContext.Provider value={this.state.theme}> <div>
<ThemedButton onClick={this.toggleTheme}> <ThemeContext.Provider value={this.state.theme}>
Change Theme <Toolbar changeTheme={this.toggleTheme} />
</ThemedButton> </ThemeContext.Provider>
</ThemeContext.Provider> <div>
<ThemedButton />
</div>
</div>
); );
} }
} }

2
examples/context/theme-detailed-theme-context.js

@ -11,5 +11,5 @@ export const themes = {
// highlight-range{1-3} // highlight-range{1-3}
export const ThemeContext = React.createContext( export const ThemeContext = React.createContext(
themes.dark themes.dark // default value
); );

55
examples/context/theme-example.js

@ -1,55 +0,0 @@
// Create a theme context, defaulting to light theme
// highlight-next-line
const ThemeContext = React.createContext('light');
class ThemeProvider extends React.Component {
render() {
// highlight-range{2-4}
return (
<ThemeContext.Provider value={this.props.theme}>
{this.props.children}
</ThemeContext.Provider>
);
}
}
class ThemedButton extends React.Component {
render() {
//highlight-range{2-4}
return (
<ThemeContext.Consumer>
{theme => <Button theme={theme} />}
</ThemeContext.Consumer>
);
}
}
const SomeComponent = props => {
// The ThemedButton receives the theme from context;
// SomeComponent does not need to know about it
// highlight-range{3}
return (
<div>
<ThemedButton />
</div>
);
};
class App extends React.Component {
render() {
// The ThemedButton button inside the ThemeProvider
// uses the dark theme while the one outside uses the
// default light theme
// highlight-range{3-5,7}
return (
<div>
<ThemeProvider theme="dark">
<SomeComponent />
</ThemeProvider>
<div>
<ThemedButton />
</div>
</div>
);
}
}
Loading…
Cancel
Save