These components are enabling seamless theming for your react applications. So as far as you don't want to pass the theme object to every component. That's why you want to use context. However, as far context feature is experimental API and it is likely to break in future releases of React you don't want to use it directly. Here theming comes to play.
If you insist on using context despite these warnings, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.
If you insist on using context despite these warnings, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.
— Context, React documentation
Regarding isolation your use of context to a small area and small areas_ in particular our very own react prophet Dan Abramov have a thing to say:
If its Function and its nested ThemeProvider then it's being applied to the theme from parent ThemeProvider. If the result is an Object it's passed down to the react tree, throws otherwise.
React High-Order component, which maps context to theme prop.
component
Required
Type: ComponentType
You need to have ThemeProvider with a theme somewhere upper the react tree after that wrap your component in withTheme and your component gets the theme as a prop. withTheme handles the initial theme object as well as theme updates.
PS. It doesn't break if you have PureComponent somewhere in between your ThemeProvider and withTheme.
Usage with Component:
import React from 'react';import { withTheme } from 'theming';const DemoBox = props => { console.log(props.theme); return (<div />);}export default withTheme(DemoBox);
We export the default ThemeContext so you can use it with the new static contextType with classes or even the new React Hooks API.
This is the context which also the exported withTheme and ThemeProvider use.