Storybook addon that enables theme switching functionality within the preview environment with support for multiple theming strategies
—
Theme switching by applying CSS classes to parent elements. This approach is ideal for CSS frameworks, traditional stylesheet-based themes, and any styling system that relies on CSS class names.
Creates a decorator that applies theme-specific CSS classes to a parent element (typically html or body).
/**
* Creates a decorator for CSS class-based theme switching
* @param config - Configuration object specifying themes and options
* @returns Storybook decorator function
*/
function withThemeByClassName<TRenderer extends Renderer = Renderer>(
config: ClassNameStrategyConfiguration
): DecoratorFunction<TRenderer>;
interface ClassNameStrategyConfiguration {
/** Mapping of theme names to CSS class names */
themes: Record<string, string>;
/** Name of the default theme */
defaultTheme: string;
/** CSS selector for the parent element (defaults to 'html') */
parentSelector?: string;
}Usage Examples:
import { withThemeByClassName } from '@storybook/addon-themes';
// Basic usage with light/dark themes
export const decorators = [
withThemeByClassName({
themes: {
light: 'light-theme',
dark: 'dark-theme',
},
defaultTheme: 'light',
}),
];
// Multiple theme classes
export const decorators = [
withThemeByClassName({
themes: {
light: 'theme-light bg-white',
dark: 'theme-dark bg-gray-900',
blue: 'theme-blue bg-blue-100',
},
defaultTheme: 'light',
}),
];
// Custom parent selector
export const decorators = [
withThemeByClassName({
themes: {
default: 'default-theme',
contrast: 'high-contrast-theme',
},
defaultTheme: 'default',
parentSelector: 'body',
}),
];The decorator automatically:
Stories can override the global theme selection:
export const DarkVariant = {
parameters: {
themes: {
themeOverride: 'dark'
}
}
};Perfect for CSS frameworks that use class-based theming:
/* Tailwind CSS example */
.light-theme {
@apply bg-white text-gray-900;
}
.dark-theme {
@apply bg-gray-900 text-white;
}
/* Bootstrap example */
.theme-light {
background-color: var(--bs-light);
color: var(--bs-dark);
}
.theme-dark {
background-color: var(--bs-dark);
color: var(--bs-light);
}Install with Tessl CLI
npx tessl i tessl/npm-storybook--addon-themes