How to use Tailwind CSS with styled-components
Updated: October 23, 2020Tailwind is a utility-first CSS framework for building custom designs. It's highly customizable and provides you all the necessary building blocks you need to build a design.
My favorite approach to style React components is CSS-in-JS. With styled-components, I can utilise tagged template literals to write actual CSS code to style my components. That's why I thought to combine the Tailwind experience with the React component model.
Installation
To get started, you need to install Tailwind and styled-components:
Configuration
Once tailwind macro
is installed, we need to add a babel-plugin-macros.config.js
file in the root folder of our project. Then we need to tell tailwind macro
to use the styled-component macro
.
This is all we need in order to write Tailwind classes inside a styled component. However, if you want to add additional Tailwind features, you can create an optional JavaScript configuration file:
Implementation
Now is the time to create our React component and styled it using the styled-components approach together with Tailwind classes:
For more information, you can have a look at Tailwind and styled-components official documentation.