This addon helps you to display a Styled-Components ThemeProvider or a custom one in your Storybook.
- Switches background color.
- Works on iframes or visual regression testing.
- Allows passing a custom implementation of your own theme provider.
- Displays a popup with all the current keys of the theme.
- You can copy individually a value from the theme.
First, install the addon
yarn add themeprovider-storybook --dev
npm install --save-dev themeprovider-storybook
Add this line to your addons.js
file (create this file inside your storybook config directory if needed).
import 'themeprovider-storybook/register';
Import and use the addDecorator
in your config.js
file.
import { addDecorator, configure } from '@storybook/react';
import { withThemesProvider } from "themeprovider-storybook";
// Options:
const themes = [
{
name: 'Theme1' // Required it's used for displaying the button label,
backgroundColor: '#fff' // Optional, it's used for setting dynamic background color on storybook
..., // Your theme keys (Check example if you need some help)
},
{
name: 'Theme2' // Required it's used for displaying the button label,
backgroundColor: '#000'// Optional, it's used for setting dynamic background color on storybook
..., // Your theme keys (Check example if you need some help)
}
]
addDecorator(withThemesProvider(themes));
configure(() => require('./stories'), module);
Thanks to @ckknight suggestion, you can easily use your own context for themeprovider.
This is just an example of a custom theme provider, probably this is not a working, just for suggesting purposes.
const ThemeContext: Context<Theme | void> = React.createContext();
const ThemeConsumer = ThemeContext.Consumer;
export default function SomeCustomImplementationOfThemeProvider(props: Props) {
const outerTheme = useContext(ThemeContext);
const themeContext = useMemo(() => mergeTheme(props.theme, outerTheme), [
props.theme,
outerTheme,
]);
if (!props.children) {
return null;
}
return <ThemeContext.Provider value={themeContext}>{props.children}</ThemeContext.Provider>;
}
On config.js file of Storybook, just pass a CustomThemeProvider
import { SomeCustomImplementationOfThemeProvider } from "src/app/CustomThemeProvider.jsx"
addDecorator(
withThemesProvider(themes),
SomeCustomImplementationOfThemeProvider
);
SomeCustomImplementationOfThemeProvider
must admit a theme
as prop.