How to setup Tailwind CSS in your React App.

How to setup Tailwind CSS in your React App.

Introduction

Tailwind CSS is a popular utility-first CSS framework that helps to quickly build modern websites and applications. In this tutorial, we'll go through the steps to set up Tailwind CSS in a React app.

Prerequisite

Make sure you have the following installed on your computer;

  • Nodejs

  • Npm

If you don't have them, you can download and install them from the official Node.js website.

Create React App

Set up your react application using the create-react-app command. Open your terminal or command prompt and enter this command:

npx create-react-app my-app

This command will create a react app with all the necessary structure that comes along with it. The time it takes for the process to complete depends on how fast your internet connection is.

Install TailwindCSS

We need to install Tailwind CSS and all its dependencies in our React app. To do so, let’s navigate to your our new react app in the terminal and install all TailwindCSS dependencies using the following command:

npm install -D tailwindcss
npx tailwindcss init

If you intend to work with tools like webpack, Rollup, Vite and Parcel, it is recommend to install Tailwind as a PostCSS plugin, you can do that using the following command:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

If you used the PostCSS command, confirm if Tailwind was added to the PostCSS configuration in your postcss.config.js file.

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

Both CLI and PostCSS require templates paths configuration in order for Tailwind to work in your react app. Inspect your tailwind.config.js file and make sure you have the following configuration:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

Next, we need to add the @tailwind directives for each of Tailwind’s layers to your main CSS file. Let’s navigate to src folder and create index.css and add the following lines.

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

Using Tailwind Classes in React

We can use Tailwind CSS classes in our React app. Go to the src/App.js file and replace its contents with the following code:

import React from 'react';
Import ‘./index.css’
function App() {
  return (
    <div className="bg-gray-200">
      <h1 className="text-4xl font-bold text-center pt-20">Welcome to my Tailwind CSS app</h1>
      <p className="text-gray-800 text-center mt-10">Let's build something amazing!</p>
    </div>
  );
}
export default App;

If you review the above code, you can see that we used Tailwind CSS classes to set the background color, font size, font weight and text alignment of our App component.