Press ESC to close
⚛️ React⚡ Vite🎨 Tailwind CSS

React + Tailwind CSS Setup

Learn how to create a React.js project with Vite and integrate Tailwind CSS for rapid UI development. Follow along step-by-step!

👨‍💻safal.me
Setup Progress0 / 6 steps completed

🚀 What You'll Learn

  • Create a new React project using Vite
  • Install and configure Tailwind CSS
  • Understand the project structure
  • Practice with interactive examples
📋 Prerequisites

📦 Node.js

You need Node.js (v18+) installed on your system.

Check your Node.js version:

Terminal
node --version

📝 Code Editor

We recommend VS Code with these extensions:

  • • Tailwind CSS IntelliSense
  • • ES7+ React Snippets
  • • Prettier

🔧 Don't have Node.js? Install it here!

Node.js is required to run React and npm (Node Package Manager). Choose your operating system below:

🪟Windows InstallationClick to expand

Option 1: Download Installer (Recommended for Beginners)

  1. Visit nodejs.org
  2. Download the LTS (Long Term Support) version
  3. Run the installer (.msi file)
  4. Follow the installation wizard (keep default options)
  5. Restart your terminal/command prompt

Option 2: Using Chocolatey (Package Manager)

If you have Chocolatey installed, run in PowerShell as Admin:

Terminal
choco install nodejs-lts

Option 3: Using Winget (Windows 10/11)

Run in PowerShell or Command Prompt:

Terminal
winget install OpenJS.NodeJS.LTS

✅ Verify installation: Open a new Command Prompt and run:

Terminal
node --version && npm --version
🍎macOS InstallationClick to expand

Option 1: Download Installer

  1. Visit nodejs.org
  2. Download the LTS version for macOS
  3. Open the .pkg file and follow the installer

Option 2: Using Homebrew (Recommended)

If you don't have Homebrew, install it first:

Terminal
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Then install Node.js:

Terminal
brew install node

Option 3: Using NVM (Node Version Manager)

Best for managing multiple Node versions:

Terminal
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

Restart terminal, then:

Terminal
nvm install --lts && nvm use --lts

✅ Verify installation: Open a new Terminal and run:

Terminal
node --version && npm --version
🐧Linux InstallationClick to expand

Ubuntu / Debian

Using NodeSource repository (recommended for latest LTS):

Terminal
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
Terminal
sudo apt-get install -y nodejs

Or using apt (may be older version):

Terminal
sudo apt update && sudo apt install nodejs npm

Fedora / RHEL / CentOS

Using dnf:

Terminal
sudo dnf install nodejs npm

Or using NodeSource:

Terminal
curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
Terminal
sudo dnf install nodejs

Arch Linux

Terminal
sudo pacman -S nodejs npm

Using NVM (Works on any Linux - Recommended)

Install NVM:

Terminal
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

Close and reopen terminal, then:

Terminal
nvm install --lts
Terminal
nvm use --lts

✅ Verify installation: Open a new terminal and run:

Terminal
node --version && npm --version

⚠️ Common Issues & Solutions

  • Permission errors on Linux/Mac: Don't use sudo with npm. Use NVM instead.
  • Command not found: Close and reopen your terminal after installation.
  • Old version installed: Use NVM to install and switch to the latest LTS version.
  • npm is slow: Try using pnpm or yarn as alternatives.

🔀 Choose Your Setup Method

Pick how you want to set up your React + Tailwind project

1

Create Your Vite + React Project

In Progress

Vite is a modern build tool that provides an extremely fast development experience. Let's create a new React project:

Create a new Vite project with React template:

Terminal
npm create vite@latest my-react-app -- --template react
💡 Pro Tip:

Replace my-react-app with your desired project name. Use lowercase letters and hyphens (e.g., my-portfolio).

Navigate into your project folder:

Terminal
cd my-react-app

🧠 Quick Quiz

What does Vite provide for React development?

2

Install Tailwind CSS

Click to expand

Now let's install Tailwind CSS along with its peer dependencies:

Install Tailwind CSS and dependencies:

Terminal
npm install -D tailwindcss@3 postcss autoprefixer

📦 What are these packages?

tailwindcssThe core Tailwind CSS framework with utility classes
postcssCSS transformer that processes Tailwind directives
autoprefixerAdds vendor prefixes for browser compatibility

Generate configuration files:

Terminal
npx tailwindcss init -p
📁 Files Created:

This creates tailwind.config.js andpostcss.config.js in your project root.

3

Configure Template Paths

Click to expand

Tell Tailwind where to find your template files so it can purge unused styles in production:

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

🎯 Understanding the Content Array

  • "./index.html" — Scans your main HTML file
  • "./src/**/*.{js,ts,jsx,tsx}" — Scans all JS/TS files in src folder

🧠 Quick Quiz

Why do we need to configure content paths in Tailwind?

4

Add Tailwind Directives to CSS

Click to expand

Replace the contents of your ./src/index.css file with Tailwind's directives:

src/index.csscss
@tailwind base;
@tailwind components;
@tailwind utilities;

📚 What do these directives do?

@tailwind base;

Injects Tailwind's base styles (Preflight) - modern CSS reset

@tailwind components;

Injects component classes and any custom components you define

@tailwind utilities;

Injects all utility classes (the main Tailwind classes you'll use)

5

Start Development Server

Click to expand

You're all set! Start the development server to see your React + Tailwind app:

Start the Vite development server:

Terminal
npm run dev

🎉 Your app is running!

Open http://localhost:5173 in your browser to see your app.

⚡ Hot Reload:

Vite provides instant hot module replacement. Any changes you make will appear immediately without refreshing the page!

6

Test Your Setup

Click to expand

Let's verify Tailwind is working! Replace your App.jsx with this code:

src/App.jsxjsx
export default function App() {
  return (
    <div className="min-h-screen bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center">
      <div className="bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4">
        <h1 className="text-3xl font-bold text-gray-800 mb-4">
          🎉 Hello Tailwind!
        </h1>
        <p className="text-gray-600 mb-6">
          Your React + Tailwind CSS setup is working perfectly!
        </p>
        <button className="w-full bg-purple-500 hover:bg-purple-600 text-white font-bold py-3 px-6 rounded-lg transition-colors">
          Get Started
        </button>
      </div>
    </div>
  )
}
✅ If you see a beautiful gradient background with a card, Tailwind is working!
🎮 Interactive React + Tailwind Practice Arena

Now it's time to practice! Below you'll find interactive editors where you can write real React.js code with Tailwind CSS styling.

✨ Write code, see live results, and learn from error messages when something goes wrong!

⚛️ React.js Basics

Learn fundamental React concepts with hands-on practice.

Exercise 1: Build a Counter with useState

🌱 Beginner
📝 Task: Create a counter that increments and decrements using React's useState hook.
✏️ App.jsx - Edit the code below!✨ Changes apply instantly
// Counter Component with useState
function Counter() {
  // useState hook creates state variable
  const [count, setCount] = useState(0);

  return (
    <div className="text-center p-6">
      <h2 className="text-3xl font-bold text-gray-800 mb-4">
        Count: {count}
      </h2>
      <div className="flex gap-3 justify-center">
        <button 
          onClick={() => setCount(count - 1)}
          className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
        >
          - Decrease
        </button>
        <button 
          onClick={() => setCount(count + 1)}
          className="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600"
        >
          + Increase
        </button>
      </div>
    </div>
  );
}
👁️ LIVE PREVIEWYour component renders here
📚 Available: useState, useEffect, useCallback (click to expand)
const [value, setValue] = useState(initialValue);
useEffect(() => {}...}, [dependencies]);

💡 Define a function component and it will render automatically!

Exercise 2: Toggle Visibility (Conditional Rendering)

🌱 Beginner
📝 Task: Show/hide content using conditional rendering with useState.
✏️ App.jsx - Edit the code below!✨ Changes apply instantly
// Toggle Component - Conditional Rendering
function Toggle() {
  const [isVisible, setIsVisible] = useState(true);

  return (
    <div className="p-6">
      <button
        onClick={() => setIsVisible(!isVisible)}
        className="px-6 py-3 bg-purple-500 text-white rounded-xl 
                   font-bold hover:bg-purple-600 transition mb-4"
      >
        {isVisible ? '🙈 Hide' : '👁️ Show'} Content
      </button>
      
      {isVisible && (
        <div className="p-4 bg-purple-100 rounded-xl text-purple-800 
                        animate-pulse">
          ✨ I'm visible! Click the button to hide me.
        </div>
      )}
    </div>
  );
}
👁️ LIVE PREVIEWYour component renders here
📚 Available: useState, useEffect, useCallback (click to expand)
const [value, setValue] = useState(initialValue);
useEffect(() => {}...}, [dependencies]);

💡 Define a function component and it will render automatically!

Exercise 3: Controlled Input (Two-way Binding)

🌱 Beginner
📝 Task: Create a controlled input that updates state as you type.
✏️ App.jsx - Edit the code below!✨ Changes apply instantly
// Controlled Input Component
function TextInput() {
  const [text, setText] = useState('');

  return (
    <div className="p-6 space-y-4">
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type something..."
        className="w-full px-4 py-3 border-2 border-gray-300 
                   rounded-xl focus:border-blue-500 focus:ring-2 
                   focus:ring-blue-200 outline-none transition"
      />
      
      <div className="p-4 bg-gray-100 rounded-xl">
        <p className="text-gray-600">You typed:</p>
        <p className="text-2xl font-bold text-blue-600">
          {text || '(start typing above)'}
        </p>
        <p className="text-sm text-gray-400 mt-2">
          Character count: {text.length}
        </p>
      </div>
    </div>
  );
}
👁️ LIVE PREVIEWYour component renders here
📚 Available: useState, useEffect, useCallback (click to expand)
const [value, setValue] = useState(initialValue);
useEffect(() => {}...}, [dependencies]);

💡 Define a function component and it will render automatically!

Exercise 4: Rendering Lists with .map()

🌿 Intermediate
📝 Task: Render a list of items using JavaScript's map() function.
✏️ App.jsx - Edit the code below!✨ Changes apply instantly
// List Rendering Component
function ItemList() {
  const [items, setItems] = useState([
    'Learn React Basics',
    'Master Tailwind CSS', 
    'Build Amazing UIs'
  ]);

  return (
    <div className="p-6">
      <h3 className="text-xl font-bold text-gray-800 mb-4">
        📝 My Todo List
      </h3>
      
      <ul className="space-y-2">
        {items.map((item, index) => (
          <li 
            key={index}
            className="p-4 bg-gradient-to-r from-orange-100 
                       to-red-100 rounded-xl flex justify-between 
                       items-center hover:shadow-md transition"
          >
            <span className="font-medium text-gray-700">
              {item}
            </span>
            <span className="text-orange-500 font-bold">
              #{index + 1}
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}
👁️ LIVE PREVIEWYour component renders here
📚 Available: useState, useEffect, useCallback (click to expand)
const [value, setValue] = useState(initialValue);
useEffect(() => {}...}, [dependencies]);

💡 Define a function component and it will render automatically!

Exercise 5: Loading States

🌿 Intermediate
📝 Task: Handle loading states with useState - essential for async operations.
✏️ App.jsx - Edit the code below!✨ Changes apply instantly
// Loading State Component
function LoadingButton() {
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState(null);

  const handleClick = () => {
    setIsLoading(true);
    
    // Simulate API call with setTimeout
    setTimeout(() => {
      setData('Data loaded successfully! 🎉');
      setIsLoading(false);
    }, 2000);
  };

  return (
    <div className="p-6 text-center">
      <button
        onClick={handleClick}
        disabled={isLoading}
        className={`px-6 py-3 rounded-xl font-bold transition
          ${isLoading 
            ? 'bg-gray-400 cursor-not-allowed' 
            : 'bg-blue-500 hover:bg-blue-600 text-white'
          }`}
      >
        {isLoading ? '⏳ Loading...' : '📦 Fetch Data'}
      </button>
      
      {data && (
        <div className="mt-4 p-4 bg-green-100 rounded-xl 
                        text-green-700 font-medium">
          {data}
        </div>
      )}
    </div>
  );
}
👁️ LIVE PREVIEWYour component renders here
📚 Available: useState, useEffect, useCallback (click to expand)
const [value, setValue] = useState(initialValue);
useEffect(() => {}...}, [dependencies]);

💡 Define a function component and it will render automatically!

Exercise 6: Dark/Light Theme Toggle

🌿 Intermediate
📝 Task: Build a theme switcher using conditional Tailwind classes.
✏️ App.jsx - Edit the code below!✨ Changes apply instantly
// Theme Toggle Component
function ThemeToggle() {
  const [theme, setTheme] = useState('light');
  const isDark = theme === 'dark';

  return (
    <div className={`p-6 rounded-xl transition-colors duration-300
      ${isDark ? 'bg-gray-900 text-white' : 'bg-white text-gray-900'}
    `}>
      <h3 className="text-xl font-bold mb-4">
        Current Theme: {theme}
      </h3>
      
      <button
        onClick={() => setTheme(isDark ? 'light' : 'dark')}
        className={`px-4 py-2 rounded-lg font-bold transition
          ${isDark 
            ? 'bg-yellow-400 text-gray-900' 
            : 'bg-gray-900 text-white'
          }
        `}
      >
        {isDark ? '☀️ Switch to Light' : '🌙 Switch to Dark'}
      </button>
    </div>
  );
}
👁️ LIVE PREVIEWYour component renders here
📚 Available: useState, useEffect, useCallback (click to expand)
const [value, setValue] = useState(initialValue);
useEffect(() => {}...}, [dependencies]);

💡 Define a function component and it will render automatically!

🎨 Tailwind CSS Styling Practice

Practice applying Tailwind CSS classes to style your components.

✨ Practice: Style a Card Component

Quick Presets:
✏️ EDIT TAILWIND CLASSES
✅ Classes look good!

Card Title

This is a sample card component.

💡 Tip: Try combining classes like bg-blue-500 text-white p-4 rounded-lg hover:bg-blue-600

🔘 Practice: Button Styles

Quick Presets:
✏️ EDIT TAILWIND CLASSES
"font-bold": Use "font-bold" for bold text
💡 Tip: Try combining classes like bg-blue-500 text-white p-4 rounded-lg hover:bg-blue-600

📐 Practice: Flexbox Layout

Quick Presets:
✏️ EDIT TAILWIND CLASSES
"items-center": Use "items-center" and/or "justify-center"
1
2
3
💡 Tip: Try combining classes like bg-blue-500 text-white p-4 rounded-lg hover:bg-blue-600
📖 Quick Reference Cheat Sheet

📏 Spacing

p-4 = padding: 1rem

m-4 = margin: 1rem

px-4 = padding-x: 1rem

gap-4 = gap: 1rem

🎨 Colors

bg-blue-500 = background

text-white = text color

border-gray-300 = border

📐 Flexbox

flex = display: flex

items-center = align

justify-between = justify

📱 Responsive

sm: = 640px+

md: = 768px+

lg: = 1024px+

✨ Effects

shadow-lg = box shadow

rounded-xl = border radius

opacity-50 = transparency

🔄 Transitions

transition-all

duration-300

hover:scale-105

🧠 Quick Quiz

Which command creates a new Vite React project?

One-Click Setup Scripts

Copy and paste these scripts to set up everything automatically! Choose your preferred method:

📁 Option 1: Create New Project in New Folder

Creates a new folder called my-react-app with everything configured:

setup-react-tailwind.shbash
# 🚀 React + Vite + Tailwind CSS Complete Setup Script
# Just copy-paste this entire block into your terminal!

PROJECT_NAME="my-react-app"

echo "🎯 Creating React + Tailwind project: $PROJECT_NAME"
echo "=================================================="

# Step 1: Create Vite project
npm create vite@latest $PROJECT_NAME -- --template react -y && \
cd $PROJECT_NAME && \

# Step 2: Install dependencies
echo "📦 Installing dependencies..." && \
npm install && \

# Step 3: Install Tailwind CSS
echo "🎨 Installing Tailwind CSS..." && \
npm install -D tailwindcss postcss autoprefixer && \
npx tailwindcss init -p && \

# Step 4: Configure tailwind.config.js
echo "⚙️ Configuring Tailwind..." && \
cat > tailwind.config.js << 'EOF'
/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
EOF

# Step 5: Configure CSS
echo "🎨 Setting up CSS..." && \
cat > src/index.css << 'EOF'
@tailwind base;
@tailwind components;
@tailwind utilities;
EOF

# Step 6: Create sample App.jsx with Tailwind
echo "📝 Creating sample App component..." && \
cat > src/App.jsx << 'EOF'
import { useState } from 'react'

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

  return (
    <div className="min-h-screen bg-gradient-to-br from-purple-900 via-blue-900 to-indigo-900 flex items-center justify-center">
      <div className="bg-white/10 backdrop-blur-lg rounded-2xl p-8 shadow-2xl border border-white/20">
        <h1 className="text-4xl font-bold text-white mb-6 text-center">
          ⚛️ React + Tailwind
        </h1>
        <p className="text-gray-300 text-center mb-6">
          Your project is ready! Start building amazing things.
        </p>
        <div className="flex flex-col items-center gap-4">
          <p className="text-6xl font-bold text-white">{count}</p>
          <div className="flex gap-3">
            <button
              onClick={() => setCount(count - 1)}
              className="px-6 py-3 bg-red-500 hover:bg-red-600 text-white font-bold rounded-xl transition-all transform hover:scale-105"
            >
              - Decrease
            </button>
            <button
              onClick={() => setCount(count + 1)}
              className="px-6 py-3 bg-green-500 hover:bg-green-600 text-white font-bold rounded-xl transition-all transform hover:scale-105"
            >
              + Increase
            </button>
          </div>
        </div>
        <p className="text-gray-400 text-sm text-center mt-6">
          Edit <code className="text-yellow-400">src/App.jsx</code> and save to see changes!
        </p>
      </div>
    </div>
  )
}

export default App
EOF

# Done!
echo ""
echo "✅ =================================="
echo "✅  SUCCESS! Project is ready! 🎉"
echo "✅ =================================="
echo ""
echo "📂 Project created at: $(pwd)"
echo ""
echo "🚀 To start development server, run:"
echo "   npm run dev"
echo ""
echo "🌐 Then open http://localhost:5173 in your browser"
echo ""
echo "Happy coding! 💻✨"

📍 Option 2: Setup in Current (Empty) Folder

Run this in an empty folder to set up the project there:

setup-in-current-folder.shbash
# 🚀 React + Tailwind Setup in CURRENT FOLDER
# Run this in an empty folder!

echo "🎯 Setting up React + Tailwind in current folder..."
echo "===================================================="

# Step 1: Create Vite project in current directory
npm create vite@latest . -- --template react -y && \

# Step 2: Install dependencies
echo "📦 Installing dependencies..." && \
npm install && \

# Step 3: Install Tailwind CSS
echo "🎨 Installing Tailwind CSS..." && \
npm install -D tailwindcss postcss autoprefixer && \
npx tailwindcss init -p && \

# Step 4: Configure tailwind.config.js
echo "⚙️ Configuring Tailwind..." && \
cat > tailwind.config.js << 'EOF'
/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
EOF

# Step 5: Configure CSS
cat > src/index.css << 'EOF'
@tailwind base;
@tailwind components;
@tailwind utilities;
EOF

echo ""
echo "✅ =================================="
echo "✅  SUCCESS! Setup complete! 🎉"
echo "✅ =================================="
echo ""
echo "🚀 Run: npm run dev"
echo "🌐 Open: http://localhost:5173"
echo ""
echo "Happy coding! 💻✨"

🔥 Option 3: Super Quick One-Liner

The fastest way - one command does it all:

one-liner.shbash
npm create vite@latest my-app -- --template react -y && cd my-app && npm i && npm i -D tailwindcss postcss autoprefixer && npx tailwindcss init -p && echo -e "@tailwind base;\n@tailwind components;\n@tailwind utilities;" > src/index.css && echo "✅ Done! Now configure tailwind.config.js and run: npm run dev"

🪟 Windows PowerShell Version

For Windows users using PowerShell:

setup-windows.ps1powershell
# 🚀 React + Tailwind Setup for Windows PowerShell
# Copy and paste this entire block!

$PROJECT_NAME = "my-react-app"

Write-Host "🎯 Creating React + Tailwind project: $PROJECT_NAME" -ForegroundColor Cyan
Write-Host "==================================================" -ForegroundColor Cyan

# Create project
npm create vite@latest $PROJECT_NAME -- --template react -y
Set-Location $PROJECT_NAME

# Install dependencies
Write-Host "📦 Installing dependencies..." -ForegroundColor Yellow
npm install

# Install Tailwind
Write-Host "🎨 Installing Tailwind CSS..." -ForegroundColor Yellow
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

# Configure tailwind.config.js
$tailwindConfig = @'
/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
'@
Set-Content -Path "tailwind.config.js" -Value $tailwindConfig

# Configure CSS
$cssContent = @'
@tailwind base;
@tailwind components;
@tailwind utilities;
'@
Set-Content -Path "src/index.css" -Value $cssContent

Write-Host ""
Write-Host "✅ ==================================" -ForegroundColor Green
Write-Host "✅  SUCCESS! Project is ready! 🎉" -ForegroundColor Green
Write-Host "✅ ==================================" -ForegroundColor Green
Write-Host ""
Write-Host "🚀 Run: npm run dev" -ForegroundColor Cyan
Write-Host "🌐 Open: http://localhost:5173" -ForegroundColor Cyan
Write-Host ""
Write-Host "Happy coding! 💻✨" -ForegroundColor Magenta
💡 After running any script:
  1. Start the dev server: npm run dev
  2. Open your browser to http://localhost:5173
  3. Edit src/App.jsx and see live changes!