This recipe assumes that you have a React app using Tailwind CSS and have just set up Storybook >=6.0 using the getting started guide. Don’t have this? Follow Tailwind's setup instructions then run:
How to setup Tailwind CSS and Storybook
Storybook.js is a fantastic tool for developing and showcasing UI components in isolation. One of the great things about it is that you can use any CSS framework you like, including Tailwind CSS.
In this post, we will:
- 🏗️ Build Tailwind next to Storybook
- 🎁 Provide Tailwind to stories
- 🧱 Use Tailwind in your components
- 🎨 Switch Tailwind themes in a click
Build Tailwind next to Storybook
As of storybook 7, as long as your project is already configured to use postCSS, you can skip this step.
To develop with Tailwind alongside your stories, storybook will need to know how to handle Tailwind's custom @tailwind
css directive. We can do this with PostCSS.
First of all, install a few extra dependencies.
Now create a postcss.config.js
file in the root of your project.
Then add the @storybook/addon-styling
to your .storybook/main.js
file with the postCss
option set to true.
Note: Using Vite, @storybook/nextjs
, or @storybook/preset-create-react-app
with react-scripts@2.0.0
and up? You don't need to set postCss
to true.
Provide Tailwind to stories
Now you can import the tailwind.css
file into your .storybook/preview.js
file. This will make Tailwind’s style classes available to all of your stories.
Use Tailwind in components
Let’s update some of our example components to use Tailwind instead. Open up Storybook to see what we have so far.
To make use of Tailwind, replace the contents of each component file with the following code:
Add a theme switcher tool
Tailwind comes out of the box with a light and dark theme. You can override those themes and add more. To get the most out of your stories, you should have a way to toggle between all of your themes.
First of all, update your tailwind.config.js
file to change themes based on a class or data-attribute. This example uses a data-attribute.
To add the switcher, add the withThemeByDataAttribute
decorator to your storybook from @storybook/addon-styling
This code will create a new toolbar menu to select your desired theme for your stories.
Get involved
Now you're ready to use Tailwind with Storybook. 🎉 Check out the example repo for a quick start.
If you use Tailwind at work, we'd love your help making an addon that automatically applies the configuration above. Join the maintainers in Discord to get involved, or jump into addon docs.