How to Add Tailwind CSS to Your Reactjs Project

Tailwind CSS to ReactJS project

Tailwind CSS is a utility-first CSS framework which is used to make your website more responsive and beautiful. It is well known modern CSS frameworks which helps to speed up the development and styling process significantly. If you’re new to Tailwind CSS please follow the official documentation of Tailwind CSS and find a good starting point at the project’s homepage at TailwindCSS.

Setting up your React project with Tailwind CSS is so simple and comprises only very few steps. In this tutorial you will learn step-by-step approach of installing Tailwind CSS into your React project and get started using Tailwind’s CSS classes for styling.

Step 1: Creating Your React Project

Creating your new React.js project is the very first step. The easiest way to create a new project is to use the create-react-app script on the command line.

npx create-react-app react-app-with-tailwind

Now, cd into the working directory.

cd react-app-with-tailwind

If everything goes well, you should be able to see your react project on the web browser when you run the following command.  

npm run start

Step 2: Install Tailwind CSS

Now install tailwindcss and its peer dependencies via npm, and then run the init command to generate both tailwind.config.js and postcss.config.js.

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Tailwind will create two files. You need to make small changes so it will works well for our Reactjs project.

  • tailwind.config.js
  • postcss.config.js

Step 4: Configuring Template Files

You need to specify the path to our Reactjs project files by adding the following configuration setting inside tailwind.config.js. Make sure to add the paths to all of your template files in your tailwind.config.js file.

module.exports = {
   content: [
     "./src/**/*.{js,jsx,ts,tsx}",
   ],
   theme: {
     extend: {},
   },
   plugins: [],
 }

Step 5: Add the Tailwind directives to your CSS

Now add the @tailwinddirectives for each of Tailwind’s layers to your ./src/index.css file.

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

That’s all. You’re good to go! Let’s make use of Tailwind’s CSS classes within our main React component in App.js.

Step 6: Use Tailwind CSS In Your React App

Add the following code to App.js. Start the development web server by using the following command. Now you should be able to see the following result in the browser.

<div className="container mx-auto bg-gray-200 rounded-xl shadow border p-8 m-10">
      <p className="text-3xl text-gray-700 font-bold mb-5">
        Welcome!
      </p>
      <p className="text-gray-500 text-lg">
        React and Tailwind CSS in action
      </p>
    </div>
npm run start

You can find code for this tutorial in this GitHub repo