Clue Mediator

Setting up Tailwind CSS in React Project - Part 2

πŸ“…February 21, 2024

In this second part of our Tailwind CSS journey, we'll dive deeper into integrating this powerful utility-first CSS framework into a React project.

Steps to setting up Tailwind CSS

  1. Install Tailwind CSS
  2. Configuring Tailwind
  3. Integrating with Create React App
  4. Styling Components

Project structure

  • shopping-cart

    • node_modules

    • src

      • assets

        • react.svg
      • App.jsx

      • index.css

      • main.jsx

    • index.html

    • package-lock.json

    • package.json

    • postcss.config.js

    • README.md

    • tailwind.config.js

    • vite.config.js

1. Install Tailwind CSS

To kick things off, let's install Tailwind CSS and its peer dependencies. Run the following command in your terminal:

npm install -D tailwindcss postcss autoprefixer

2. Configuring Tailwind

Run the following command to configure tailwind.

npx tailwindcss init -p

Now, you will see the tailwind.config.js and postcss.config.js files are auto-created in the root of your project. This is where you can customize Tailwind to suit your project's needs.

tailwind.config.js

/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

postcss.config.js

export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

3. Integrating with Create React App

Open your src/index.css file and import Tailwind's base styles:

index.css

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

4. Styling Components

Now, let's apply Tailwind styles to React components. Replace the styles in your component with Tailwind classes:

App.js

function App() {
  return (
    <h1 className="text-3xl text-blue-700 font-bold underline">
      Hello world!
    </h1>
  )
}

export default App

Conclusion

Congratulations! You've successfully set up Tailwind CSS in your React project. This powerful combination allows for rapid development without sacrificing flexibility. Experiment with Tailwind's extensive utility classes and watch your UI come to life effortlessly.

Happy Coding!

"Coding is like solving puzzles – it may be challenging, but the satisfaction of figuring it out is unbeatable!"

Demo & Source Code

GitHub Repository