How to install Tailwind CSS in React

in this section we will see how to add tailwind css in react js. we will also create tailwind configure file with postCSS and purge tailwind css class file into minimal size.


Setup Tailwind CSS with React


Create react app

Installing a fresh new react application.

npx create-react-app react-app

Next, Move to the directory

cd react-app


Install Tailwind CSS via npm

Install tailwind css via npm. Remember tailwind requires Node.js 12.13.0 or higher.

npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9


Install CRACO and setup configure 

Next, install CRACO to setup tailwind configurtion 

npm install @craco/craco

After craco install you need to modify package.json

Before package.json

{
    "scripts": {
     "start": "react-scripts start",
     "build": "react-scripts build",
     "test": "react-scripts test",
      "eject": "react-scripts eject"
    },
}

After package.json

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


Next, you need to create craco.config.js file and add tailwindcss and autoprefixer as PostCSS plugins.

craco.config.js

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


Include Tailwind in your CSS File

First you need to remove default css code and put tailwind css directive to include Tailwind’s base, components, and utilities.

src/index.css

/* ./src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

.btn{
  @apply py-2 px-6 rounded;
}
.btn-blue {
  @apply  bg-blue-500 text-blue-100;
}


Create tailwind configuration file

Next, generate your tailwind.config.js file.

npx tailwindcss-cli@latest init

Now, you can edit tailwind.config.js

Before tailwind.config.js

module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}
react folder structure

react folder structure


After tailwind.config.js

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

// src/App.js

import './App.css';

function App() {
  return (
    <div className="App mt-20">
      <div>
        <h1 className="text-4xl font-bold text-indigo-600">
          React with Tailwind CSS
        </h1>
        <div className="flex justify-center">
          <button className="btn btn-blue">Button</button>
        </div>
      </div>
    </div>
  );
}

export default App;


run command

npm run build 
npm start
or
yarn build
yarn start  



Tags: