I've been building a React web application with a dynamic theme feature using the emotion-theming library. This allows users to switch between different environments, each with its own unique theme. To achieve this, I created my own CustomThemeProvider which dynamically changes the theme based on the selected environment. Here's the code snippet:
export interface CustomThemeContextValue {
customTheme?: Theme;
setCustomTheme: (theme: Theme) => void;
};
const CustomThemeContext = React.createContext<CustomThemeContextValue>({
customTheme: undefined,
setCustomTheme: (theme) => { }
});
interface CustomThemeProviderProps {
}
export const CustomThemeProvider: FC<CustomThemeProviderProps> = (props) => {
const [customTheme, setCustomTheme] = useState<Theme>(theme);
const context: CustomThemeContextValue = React.useMemo(() => ({
customTheme,
setCustomTheme
}), [customTheme, setCustomTheme]);
return (
<CustomThemeContext.Provider value={context}>
<ThemeProvider theme={customTheme} {...props} />
</CustomThemeContext.Provider>
);
};
export const useCustomTheme = () => {
const context = React.useContext(CustomThemeContext);
if (!context) {
throw new Error('useCustomTheme must be used within a CustomThemeProvider');
}
return context;
};
The provider is implemented at the root level as shown below:
const Root = () => {
return (
<StrictMode>
<CustomThemeProvider>
<Normalize />
<Global styles={globalStyle} />
<App />
</CustomThemeProvider>
</StrictMode>
);
};
This setup works well, and I can access the theme in function components using the emotion useTheme hook like this:
const theme: Theme = useTheme();
However, I'm now trying to figure out how to extract the theme from the emotion ThemeProvider and utilize it in specific scenarios. Can I use it in a context like this example below?
export const style: Interpolation = {
cssProp: value
};
Or can I apply it in a context where styled.button comes into play, such as:
const Button: FC<HTMLProps<HTMLButtonElement> & ButtonProps> = styled.button([]);
Additionally, can I leverage it within the emotion/core method css() like demonstrated here?
const style = css({
cssProp: value
});
Finding concrete answers to these queries through Google has proven challenging, so any assistance from fellow developers would be greatly appreciated.