How to Use Tailwind CSS in React (2020 Guide)

Published on 20.10.2020

In the world of front-end development, Tailwind CSS has emerged as a powerful utility-first CSS framework that allows you to build highly customizable and responsive user interfaces without the need for writing custom CSS classes. It has become a popular choice for styling React applications due to its flexibility, ease of use, and rapid development speed.

In this guide, we’ll walk through why Tailwind CSS became a favorite among developers, how to set it up in Create React App and Next.js, and how to write clean, reusable styles using utility classes.


Why Tailwind Became a Popular Choice for Styling

Before Tailwind CSS, many developers used traditional CSS or preprocessor libraries like Sass to style their React applications. While these tools are powerful, they can lead to bloated stylesheets, unnecessary class names, and hard-to-maintain codebases, especially as your application grows.

Tailwind CSS addresses these issues by offering a utility-first approach to styling. Instead of writing complex, reusable CSS classes, you use predefined utility classes directly in your JSX to apply styles. This results in cleaner code, more predictable styling, and a more maintainable codebase.

Key Benefits of Tailwind CSS:

  • Utility-first: It offers a set of atomic utility classes that can be used directly in your JSX.
  • Customization: You can easily extend Tailwind’s default configuration to match your project’s unique design requirements.
  • Rapid Prototyping: It allows for faster development with minimal setup, making it ideal for creating prototypes and UI components quickly.
  • No naming collisions: Since classes are small, reusable utilities, there’s no need to worry about naming collisions or deeply nested selectors.

By using Tailwind, you can focus on building your app’s UI without spending time on writing custom CSS for each component.


Setting Up Tailwind CSS in Create React App

To get started with Tailwind in Create React App, follow these steps:

1. Install Tailwind CSS

First, you’ll need to install Tailwind CSS and its dependencies. Open your terminal and run the following commands:

# Install Tailwind CSS via npm
npm install tailwindcss postcss autoprefixer

# Create the Tailwind configuration file
npx tailwindcss init

This will generate a tailwind.config.js file where you can customize your Tailwind setup (e.g., colors, spacing, fonts, etc.).

2. Configure Tailwind in postcss.config.js

Next, you’ll need to create or update the postcss.config.js file in your project’s root directory to use Tailwind and Autoprefixer:

// postcss.config.js
module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
  ],
};

3. Add Tailwind to your CSS

Now, open the src/index.css (or wherever your global styles are located) and import Tailwind’s base styles by adding the following lines to the top of the file:

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

These three directives import Tailwind’s base styles, components, and utility classes into your project.

4. Start Your Development Server

Once everything is set up, start your development server by running:

npm start

Tailwind CSS will now be ready to use, and you can start applying utility classes directly in your React components.


Setting Up Tailwind CSS in Next.js

If you’re using Next.js, setting up Tailwind is just as easy. Here’s how you can get it up and running:

1. Install Tailwind CSS

Open your terminal and install Tailwind along with the required dependencies:

# Install Tailwind CSS, PostCSS, and Autoprefixer
npm install tailwindcss postcss autoprefixer

Then, generate the Tailwind configuration file:

npx tailwindcss init

2. Configure PostCSS

Next, create or update the postcss.config.js file in the root directory:

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};

3. Add Tailwind to Your Global CSS

In Next.js, you can add Tailwind directly to your global CSS file, typically located at styles/globals.css:

/* styles/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

4. Run Your Next.js App

Finally, start your Next.js app by running:

npm run dev

Your Next.js app is now ready to use Tailwind CSS.


Writing Clean, Reusable Styles with Utility Classes

One of the best things about Tailwind CSS is that you don’t have to write a lot of custom CSS. Instead, you can use utility classes to style your components directly in your JSX. Here’s how to write clean and reusable styles:

1. Use Utility Classes for Layout

Tailwind gives you utility classes for positioning, spacing, and layout:

// Example: Centering a component
function CenteredBox() {
  return (
    <div className="flex justify-center items-center h-screen">
      <div className="p-4 bg-blue-500 text-white rounded">
        Centered Box
      </div>
    </div>
  );
}

In this example:

  • flex sets the layout to flexbox.
  • justify-center centers horizontally.
  • items-center centers vertically.
  • h-screen sets the height to 100% of the viewport height.

2. Use Custom Classes for Reusability

You can create reusable components by combining utility classes into custom classes when needed. You can do this by using CSS-in-JS solutions or combining classes in Tailwind’s @apply directive.

Example of Reusable Button Component:

function Button({ label }) {
  return (
    <button className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-700 focus:outline-none">
      {label}
    </button>
  );
}

Here:

  • The button has padding, background color, text color, rounded corners, and hover/focus states using Tailwind’s utility classes.

3. Customize Tailwind’s Default Configuration

Tailwind’s configuration file (tailwind.config.js) allows you to extend the default utility classes to match your project’s design system. For instance, you can add custom colors, spacing values, or fonts:

// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        primary: '#3490dc',
        secondary: '#ffed4a',
      },
    },
  },
};

This way, you can maintain a consistent design across your project and improve the reusability of your components.


Conclusion

Tailwind CSS is an incredibly powerful and flexible tool for styling React applications. Its utility-first approach simplifies the process of writing and maintaining CSS, especially for large projects. By using Tailwind’s utility classes directly in your JSX, you can quickly build clean, responsive UIs without having to worry about naming conventions or deeply nested styles.

Whether you’re using Create React App or Next.js, setting up Tailwind is straightforward, and you can start building your UI in no time. With the ability to customize the framework and use reusable components, Tailwind makes it easier to scale your application’s styles as your project grows.

If you haven’t tried Tailwind yet, it’s definitely worth considering for your next React project. It’s fast, flexible, and integrates seamlessly with modern front-end frameworks.

Let me know if you have any questions or need further clarification on the setup or usage of Tailwind in React!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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