Site logo
Tác giả
  • avatar Nguyễn Đức Xinh
    Name
    Nguyễn Đức Xinh
    Twitter
Ngày xuất bản
Ngày xuất bản

Hướng Dẫn Cài Đặt Tailwind CSS trong React: Setup và Tối Ưu Hoá Styling

Tổng Quan

Hướng dẫn này sẽ chỉ bạn cách cài đặt Tailwind CSS trong React projects một cách nhanh chóng và hiệu quả. Tailwind CSS là utility-first framework giúp bạn styling trực tiếp trong JSX mà không cần viết CSS riêng biệt.

Các Phương Pháp Cài Đặt Chính

  1. Vite + React (Khuyến nghị 2024+)
  2. Create React App (Legacy)
  3. React Router

Yêu Cầu Hệ Thống

Trước khi cài đặt Tailwind CSS, đảm bảo bạn có:

  • React Project: Đã setup React với Vite, CRA, hoặc build tool khác
  • Node.js: Version 20.19+ hoặc mới hơn
  • Package Manager: NPM, Yarn, hoặc PNPM

Cách 1: Cài Đặt Với Vite (Khuyến Nghị 2024+)

Phương pháp mới nhất và được khuyến nghị từ Tailwind CSS team.

Bước 2: Cài Đặt Tailwind CSS(Version 4.1)

# Cài đặt Tailwind với Vite plugin mới
pnpm install tailwindcss @tailwindcss/vite

Bước 3: Cấu Hình Vite Plugin

Cập nhật vite.config.ts:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'

export default defineConfig({
  plugins: [
    react(),
    tailwindcss(), // Thêm Tailwind plugin
  ],
})

Bước 4: Import Tailwind CSS

Tạo hoặc cập nhật src/index.css:

@import "tailwindcss";

/* Custom styles (tùy chọn) */
@layer components {
  .btn {
    @apply px-4 py-2 rounded-lg font-medium transition-colors;
  }
  
  .btn-primary {
    @apply bg-blue-600 hover:bg-blue-700 text-white;
  }
  
  .btn-secondary {
    @apply bg-gray-200 hover:bg-gray-300 text-gray-900;
  }
}

Bước 5: Import CSS Vào React

Trong src/main.jsx hoặc src/main.tsx:

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css' // Import Tailwind CSS

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

Bước 6: Chạy Development Server

npm run dev

Bước 7: Test Installation

Cập nhật src/App.tsx:

import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";

function App() {
  const [count, setCount] = useState(0);

  return (
    <div className="min-h-screen bg-gray-900 text-white flex flex-col items-center justify-center p-8">
      <div className="flex gap-8 mb-8">
        <a 
          href="https://vite.dev" 
          target="_blank"
          className="block transition-transform hover:scale-110 hover:drop-shadow-[0_0_2em_#646cffaa]"
        >
          <img 
            src={viteLogo} 
            className="h-24 w-24 transition-transform hover:rotate-180 duration-1000" 
            alt="Vite logo" 
          />
        </a>
        <a 
          href="https://react.dev" 
          target="_blank"
          className="block transition-transform hover:scale-110"
        >
          <img 
            src={reactLogo} 
            className="h-24 w-24 animate-spin-slow hover:drop-shadow-[0_0_2em_#61dafbaa]" 
            alt="React logo" 
            style={{ animation: 'spin 20s linear infinite' }}
          />
        </a>
      </div>
      
      <h1 className="text-4xl font-bold mb-8 text-center">Vite + React</h1>
      
      <div className="bg-gray-800 p-8 rounded-lg border border-gray-700 text-center max-w-md">
        <button 
          onClick={() => setCount((count) => count + 1)}
          className="bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-6 rounded-lg transition-colors duration-200 mb-4"
        >
          count is {count}
        </button>
        <p className="text-gray-300">
          Edit <code className="bg-gray-700 text-orange-300 px-2 py-1 rounded text-sm">src/App.tsx</code> and save to test HMR
        </p>
      </div>
      
      <p className="text-gray-400 text-center mt-8 max-w-md leading-relaxed">
        Click on the Vite and React logos to learn more
      </p>
    </div>
  );
}

export default App;

Troubleshooting Cài Đặt

Lỗi Thường Gặp

  1. "tailwindcss command not found"

    # Đảm bảo cài đặt global hoặc sử dụng npx
    npx tailwindcss init
    
  2. Styles không được apply

    # Kiểm tra CSS import trong main.jsx/tsx
    # Đảm bảo content paths trong config đúng
    
  3. Build lỗi với Vite

    # Restart dev server
    npm run dev
    
    # Hoặc clear cache
    rm -rf node_modules/.vite
    npm run dev
    
  4. HMR không hoạt động

    # Với Vite + @tailwindcss/vite, HMR tự động
    # Nếu vẫn lỗi, restart server
    

Debug Commands

# Build CSS manually để test
npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch

# Kiểm tra version
npm list tailwindcss

Cấu Hình Sau Cài Đặt

Cấu Hình Cơ Bản (Nếu Cần)

Với phương pháp mới sử dụng @tailwindcss/vite, bạn không cần tạo tailwind.config.js cho setup cơ bản. Tuy nhiên, nếu muốn custom:

// tailwind.config.js (tùy chọn)
export default {
  theme: {
    extend: {
      colors: {
        brand: {
          50: '#f0f9ff',
          500: '#0ea5e9', 
          900: '#0c4a6e',
        }
      }
    }
  }
}

Development Tools Setup

VS Code Extensions

  1. Tailwind CSS IntelliSense - Autocomplete cho classes
  2. PostCSS Language Support - Syntax highlighting
  3. Prettier - Code formatting

Prettier Configuration

npm install -D prettier prettier-plugin-tailwindcss

Tạo .prettierrc:

{
  "plugins": ["prettier-plugin-tailwindcss"]
}

Environment Variables (Tùy Chọn)

# .env.local
VITE_THEME_PRIMARY=#3b82f6
VITE_THEME_SECONDARY=#64748b

Sử dụng trong CSS:

:root {
  --color-primary: env(VITE_THEME_PRIMARY, #3b82f6);
}

Kết Luận Cài Đặt

Bây giờ bạn đã sẵn sàng bắt đầu build UI với Tailwind CSS trong React! 🚀

Tài liệu Tham Khảo