Storybook's Themes addon allows you to switch between multiple themes for your components inside of the preview in Storybook .
To make your themes accessible to your stories, @storybook/addon-themes
exposes three decorators for different methods of theming.
For libraries that expose themes to components through providers, such as Material UI , Styled-components , and Emotion , use the withThemeFromJSXProvider
.
import { withThemeFromJSXProvider } from '@storybook/addon-themes' ;
import { createGlobalStyle , ThemeProvider } from 'styled-components' ;
import { lightTheme , darkTheme } from '../src/themes' ;
const GlobalStyles = createGlobalStyle `
body {
font-family: "Nunito Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
` ;
const preview = {
decorators : [
withThemeFromJSXProvider ({
themes : {
light : lightTheme ,
dark : darkTheme ,
}
defaultTheme : 'light' ,
Provider : ThemeProvider ,
GlobalStyles ,
})
]
} ;
export default preview ;
For libraries that rely on CSS classes on a parent element to determine the theme, you can use the withThemeByClassName
decorator.
import { withThemeByClassName } from '@storybook/addon-themes' ;
import '../src/index.css' ; // Your application's global CSS file
const preview = {
decorators : [
withThemeByClassName ({
themes : {
light : '' ,
dark : 'dark' ,
} ,
defaultTheme : 'light' ,
}) ,
] ,
} ;
export default preview ;
For libraries that rely on data attributes on a parent element to determine the theme, you can use the withThemeByDataAttribute
decorator.
import { withThemeByDataAttribute } from '@storybook/addon-themes' ;
import '../src/index.css' ; // Your application's global CSS file
const preview = {
decorators : [
withThemeByDataAttribute ({
themes : {
light : 'light' ,
dark : 'dark' ,
} ,
defaultTheme : 'light' ,
attributeName : 'data-theme' ,
}) ,
] ,
} ;
export default preview ;