I\'m trying to find the proper way to define some components which could be used in a generic way:
See all other answers
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. 1
Disclaimer: This is an updated answer, the previous one used the old context API
It is based on Consumer / Provide principle. First, create your context
const { Provider, Consumer } = React.createContext(defaultValue);
Then use via
{children} /* potential consumers */
and
{value => /* render something based on the context value */}
All Consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. The propagation from Provider to its descendant Consumers is not subject to the shouldComponentUpdate method, so the Consumer is updated even when an ancestor component bails out of the update. 1
Full example, semi-pseudo code.
import React from 'react';
const { Provider, Consumer } = React.createContext({ color: 'white' });
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: { color: 'black' },
};
}
render() {
return (
);
}
}
class Toolbar extends React.Component {
render() {
return (
Consumer can be arbitrary levels deep
{value => The toolbar will be in color {value.color}
}
);
}
}
1 https://facebook.github.io/react/docs/context.html