How to add Tailwind css in React JS application ?

Follow on LinkedIn

This article is updated, Please checkout the updated version of add tailwind to react

Tailwind CSS is a utility first CSS framework, It can be composed to build any design.

Create react app doesn’t support post CSS8 yet, so you need to install the tailwind CSS version 2.0 post CSS7 compatibility build.

npm installD tailwindcss@npm:@tailwindcss/postcss7compat postcss@^7 autoprefixer@^9

autoprefixer and tailwindcss/form doesn’t come with default tailwind install so we are adding these additionally.

Now we need to install a new utility craco because create react app doesn’t support post CSS.

craco stands for create react app configuration override.

npm install @craco/caraco

Note : if you get any error related to react scripts then run this command and reinstall above craco command.

npm install reactscripts@4

After installing craco, open package.json file and update scripts property with following code.

“scripts”: {
    “start”: “craco start”,
    “build”: “craco build”,
    “test”: “craco test”,
    “eject”: “react-scripts eject”
  },

Now we need to create a craco.config.js file inside the root location.

module.exports = {
    style: {
      postcss: {
        plugins: [
          require(‘tailwindcss’),
          require(‘autoprefixer’),
        ],
      },
    },
  }

Now we need to set tailwind config file, To create tailwind.config.js file we need to install a npm command.

npx tailwindcsscli@latest init

This above command will crate tailwind.config.js file.

module.exports = {
  purge: [],
  darkMode: false, // or ‘media’ or ‘class’
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

Now configure tailwind to remove unused styles in produciton.

module.exports = {
  purge: [‘./src/**/*.{js,jsx,ts,tsx}’, ‘./public/index.html’],
   darkMode: false, // or ‘media’ or ‘class’
   theme: {
     extend: {},
   },
   variants: {
     extend: {},
   },
   plugins: [],
 }

To include tailwind in our project now we just need to add few tailwind imports to index.css file.

@tailwind base;
@tailwind components;
@tailwind utilities;

Now the tailwind is successfully added to our project.

Now we can use tailwind css class in our react js components, here we are adding some tailwind classes in App component and making text font thin and increasing its size.

import logo from ‘./logo.svg’;
import ‘./App.css’;
function App() {
  return (
    <div className=“container mx-auto mt-3 font-thin”>
      <h1 className=“text-5xl”>Tailwind css working now!</h1>
    </div>
  );
}
export default App;

Output for the above code is :

I hope you like this blog, feel free to ask if you have any question.

Related Posts

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

×