The Ultimate Guide to Dark Mode with Vite, React, and Tailwind in Storybook 2023
Sergio Serrano
2 min read
As developers, we're no strangers to the challenges of ensuring our components look impeccable in both light and dark mode. With the latest features of Tailwind CSS and Storybook as our testing playground, we're about to turn those challenges into triumphs.
Step 1: Setting Up Your Vite Project
pnpm create vite
Navigate to your project directory and install the required dependencies.
cd my-project
pnpm install
Step 2: Integrating Tailwind CSS
- We need to install Tailwind CSS in our project.
pnpm install -D tailwindcss postcss autoprefixer
- Generate
tailwind.config.js
andpostcss.config.js
files
pnpm dlx tailwindcss init -p
- Configure Tailwind by updating
tailwind.config.js
, setting the darkMode.
/** @type {import('tailwindcss').Config} */
export default {
darkMode: ['class', '[data-mode="dark"]'],
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
- Inject Tailwind into your main CSS at
/src/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;
Step 3: Setting Up Storybook
- Initialize Storybook if you haven't already:
pnpm dlx storybook@latest init
- Integrate Tailwind by importing its CSS into the
/.storybook/preview.ts
import 'tailwindcss/tailwind.css' // <-- HERE
import type { Preview } from "@storybook/react";
const preview: Preview = {
parameters: {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
},
};
export default preview;
You can now utilize Tailwind within Storybook. Let's proceed with configuring the dark mode.
- Add
@storybook/addon-themes
to the project.
pnpm add -D @storybook/addon-themes
- Add the new theme to the main.ts in Storybook
/.storybook/main.ts
import type { StorybookConfig } from "@storybook/react-vite";
const config: StorybookConfig = {
stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"],
addons: [
"@storybook/addon-links",
"@storybook/addon-essentials",
"@storybook/addon-onboarding",
"@storybook/addon-interactions",
"@storybook/addon-themes", // <-- HERE
],
framework: {
name: "@storybook/react-vite",
options: {},
},
docs: {
autodocs: "tag",
},
};
export default config;
- Add the themes in the preview file
/.storybook/preview.ts
import 'tailwindcss/tailwind.css'
import type { Preview } from "@storybook/react";
import { withThemeByClassName } from '@storybook/addon-themes'
const preview: Preview = {
parameters: {
actions: { argTypesRegex: '^on[A-Z].*' },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
},
decorators: [
withThemeByClassName({
themes: {
light: 'light',
dark: 'dark',
},
defaultTheme: 'light',
}),
],
}
export default preview
Happy coding!
1
Subscribe to my newsletter
Read articles from Sergio Serrano directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by