Toggle between light and dark mode in Storybook
—
React hook and component integration patterns for accessing and responding to theme changes in Storybook Dark Mode.
React hook that returns the current dark mode state and automatically updates when the theme changes.
/**
* Returns the current state of storybook's dark-mode
* @returns boolean indicating if dark mode is currently active
*/
function useDarkMode(): boolean;Usage Examples:
import React from 'react';
import { useDarkMode } from 'storybook-dark-mode';
// Basic theme-aware component
function MyComponent() {
const isDark = useDarkMode();
return (
<div style={{
backgroundColor: isDark ? '#333' : '#fff',
color: isDark ? '#fff' : '#333'
}}>
Current theme: {isDark ? 'Dark' : 'Light'}
</div>
);
}
// Theme provider wrapper
function ThemeWrapper({ children }) {
const isDark = useDarkMode();
return (
<ThemeContext.Provider value={isDark ? darkTheme : lightTheme}>
{children}
</ThemeContext.Provider>
);
}
// Using with Storybook decorators
export const decorators = [
(renderStory) => (
<ThemeWrapper>
{renderStory()}
</ThemeWrapper>
)
];The hook uses React's useState and useEffect to:
Internal Behavior:
DARK_MODE_EVENT_NAME eventsimport React from 'react';
import { useDarkMode } from 'storybook-dark-mode';
import { ThemeProvider } from 'styled-components';
const darkTheme = { bg: '#333', color: '#fff' };
const lightTheme = { bg: '#fff', color: '#333' };
function StyledThemeWrapper({ children }) {
const isDark = useDarkMode();
return (
<ThemeProvider theme={isDark ? darkTheme : lightTheme}>
{children}
</ThemeProvider>
);
}import React from 'react';
import { useDarkMode } from 'storybook-dark-mode';
function ClassBasedThemeWrapper({ children }) {
const isDark = useDarkMode();
return (
<div className={isDark ? 'dark-theme' : 'light-theme'}>
{children}
</div>
);
}import React from 'react';
import { useDarkMode } from 'storybook-dark-mode';
function CSSVariableThemeWrapper({ children }) {
const isDark = useDarkMode();
React.useEffect(() => {
const root = document.documentElement;
if (isDark) {
root.style.setProperty('--bg-color', '#333');
root.style.setProperty('--text-color', '#fff');
} else {
root.style.setProperty('--bg-color', '#fff');
root.style.setProperty('--text-color', '#333');
}
}, [isDark]);
return <>{children}</>;
}Install with Tessl CLI
npx tessl i tessl/npm-storybook-dark-mode