One of the new things in React 16.3.0 is a new context
API:
Typically, data in a React application is passed top-down (parent to child) via
props
. But sometimes it’s useful to pass values through multiple levels of abstraction without involving each intermediate. Examples include a locale, or a UI theme.Context in React provides a mechanism for a child component to access a value in an ancestor component. From now on we’ll refer to the ancestor as the provider and the child as the consumer.
Below is an example on how to use it. Create a context first, and then create a Provider along with one (or more) Consumer(s) that will be able to read the data from the Provider using its own context
prop.
import React from 'react';
import {render} from 'react-dom';
const styles = {
dark: {
backgroundColor: 'black',
color: 'white',
},
light: {
backgroundColor: 'white',
color: 'black',
},
};
// 1. Create a context
const ThemeContext = React.createContext();
// 2. Our app contains a provider for ThemeContext.
// Anything we store into the ThemeContext will be accessible to a consumer
class App extends React.Component {
state = {
theme: 'light'
};
toggleTheme = () => {
this.setState(({ theme }) => ({
theme: theme === 'light' ? 'dark' : 'light',
}));
}
render() {
return (
<ThemeContext.Provider value={this.state}>
<button onClick={this.toggleTheme}>toggle theme</button>
<ThemableDiv />
</ThemeContext.Provider>
);
}
}
// 3. A consumer with access to the data contained in ThemeContext
class ThemableDiv extends React.PureComponent {
render() {
return(
<ThemeContext.Consumer>
{context => <div style={styles[context.theme]}>{context.theme}</div>}
</ThemeContext.Consumer>
);
}
}
render(<App />, document.getElementById('root'));
In case you want to play with the code:
Note: The example is based on an example by Kent C. Dodds.
Consider donating.
I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!
Leave a comment