How to use Tailwind CSS with styled-components
Tailwind 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:
1npm install tailwind.macro@next --save2npm install styled-components --save
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
.
1// babel-plugin-macros.config.js2module.exports = {3 tailwind: {4 config: './src/tailwind.config.js',5 styled: 'styled-components/macro',6 },7};
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:
1// src/tailwind.config.js2module.exports = {3 purge: [],4 theme: {5 extend: {},6 },7 variants: {},8 plugins: [],9};
Implementation
Now is the time to create our React component and styled it using the styled-components approach together with Tailwind classes:
1// src/pages/test.js2import React from 'react';3import styled from 'styled-components/macro';4import tw from 'tailwind.macro';56// styles7const Header = styled.header`89`;1011const Test = () => (12 <div css={tw`text-center`}>13 <Header>14 <p css={tw`text-blue-300`}>15 Using <code>Tailwind</code> and <code>styled-components</code> together.16 </p>17 </Header>18 </div>19);2021export default Test;
For more information, you can have a look at Tailwind and styled-components offical documentation.