This recipe assumes that you have a React app using Tailwind CSS and have just set up Storybook >=7.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
Install @storybook/addon-styling
Add the @storybook/addon-styling
package to your DevDependencies
Auto-config
As of version 1.3, @storybook/addon-styling
offers a codemod for to automatically configure your storybook with Tailwind.
To try it out, run the following script:
If the codemod didn't work, please let us know in this GitHub issue so we can continue to make the codemod even better. In the meantime, the instructions below will get you up and running in no time.
Manual
Build Tailwind next to Storybook
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 and pass it postcss
in options.postCss.implementation
.
📣 If you are using Vite, @storybook/nextjs
, @storybook/angular
, or @storybook/preset-create-react-app
with react-scripts@2.0.0
, then leave the options object empty.
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.