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
To develop with Tailwind alongside your stories, you’ll need a development environment that runs two independent but coordinated processes using
Then add these updated scripts to your
Now you can import the
tailwind.css file into your
.storybook/preview-head.html file. This will make Tailwind’s style classes available to all of your stories.
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:
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, declare a global type named "theme" in
.storybook/preview.js and give it a list of supported themes to choose from.
This code will create a new toolbar menu to select your desired theme for your stories.
There needs to be a way to tell Tailwind to use the theme that is selected in the toolbar. To do that, This can be done using a decorator.
Below I created a new file in
withTailwindTheme.decorator.js that will take the global theme value and update the current theme.
Now all we have to do is give this decorator to Storybook to wrap our stories in. Add the decorator to the
decorators array in
Now you're ready to use Tailwind with Storybook. 🎉 Check out the example repo for a quick start.