แสดงบทความที่มีป้ายกำกับ Dark Mode แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ Dark Mode แสดงบทความทั้งหมด

วันศุกร์ที่ 28 มีนาคม พ.ศ. 2568

🌙 การทำ Dark Mode ใน Next.js: ให้เว็บของคุณเท่ขึ้นแบบมืออาชีพ!

เบื่อไหม? กับเว็บที่สว่างจ้าจนตาล้า 😵‍💫 ถ้าคุณอยากให้ผู้ใช้เลือกได้ว่าอยากใช้ โหมดสว่าง (Light Mode) หรือ โหมดมืด (Dark Mode) ใน Next.js เรามีวิธีง่ายๆ ให้คุณลองทำ!

ในบทความนี้ เราจะมาเจาะลึก การทำ Dark Mode ใน Next.js แบบครบทุกวิธี ทั้งใช้ CSS Variables, useState, localStorage และไลบรารีเสริม เช่น Next Themes กับ Tailwind CSS พร้อมตัวอย่างโค้ดที่เอาไปใช้ได้เลย! 🚀


🔥 ทำไมต้องมี Dark Mode?

✅ ข้อดีของ Dark Mode

  • ช่วยลดอาการล้าสายตา 👀 (สำหรับคนที่ใช้เว็บตอนกลางคืน)
  • ประหยัดแบตเตอรี่ 🔋 (โดยเฉพาะจอ OLED)
  • ดูเท่! 😎 หลายเว็บใหญ่ๆ ก็ใช้ เช่น YouTube, Twitter


🛠 วิธีทำ Dark Mode ใน Next.js

🚀 1. ใช้ CSS Variables + useState

วิธีนี้เหมาะกับ:
✅ เว็บที่ไม่ซับซ้อนมาก
✅ ไม่ต้องใช้ไลบรารีเสริม


👨‍💻 ขั้นตอนการทำ

1️⃣ สร้าง globals.css และกำหนด Theme

แก้ไขไฟล์ styles/globals.css

:root {
  --bg-color: #ffffff;
  --text-color: #000000;
}

.dark-mode {
  --bg-color: #121212;
  --text-color: #ffffff;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: background 0.3s, color 0.3s;
}

2️⃣ เพิ่มปุ่มสลับโหมดใน index.js

เปิดไฟล์ pages/index.js แล้วเพิ่มโค้ดนี้

import { useState } from "react";

export default function Home() {
  const [darkMode, setDarkMode] = useState(false);

  const toggleDarkMode = () => {
    setDarkMode(!darkMode);
    document.body.classList.toggle("dark-mode");
  };

  return (
    <div style={{ textAlign: "center", marginTop: "50px" }}>
      <h1>Dark Mode in Next.js 🌙</h1>
      <button
        onClick={toggleDarkMode}
        style={{
          padding: "10px 20px",
          fontSize: "18px",
          cursor: "pointer",
          background: darkMode ? "#fff" : "#333",
          color: darkMode ? "#000" : "#fff",
          border: "none",
          borderRadius: "5px",
        }}
      >
        {darkMode ? "Switch to Light Mode ☀️" : "Switch to Dark Mode 🌙"}
      </button>
    </div>
  );
}

🛠 2. ใช้ localStorage จำค่าโหมด

ปัญหา: ถ้ารีเฟรชหน้าเว็บ ค่าโหมดที่เลือกไว้จะหายไป
ทางแก้: ใช้ localStorage จำค่าการตั้งค่าของผู้ใช้

อัปเดตโค้ด index.js

import { useState, useEffect } from "react";

export default function Home() {
  const [darkMode, setDarkMode] = useState(false);

  useEffect(() => {
    const savedTheme = localStorage.getItem("theme");
    if (savedTheme === "dark") {
      setDarkMode(true);
      document.body.classList.add("dark-mode");
    }
  }, []);

  const toggleDarkMode = () => {
    setDarkMode(!darkMode);
    if (!darkMode) {
      document.body.classList.add("dark-mode");
      localStorage.setItem("theme", "dark");
    } else {
      document.body.classList.remove("dark-mode");
      localStorage.setItem("theme", "light");
    }
  };

  return (
    <div style={{ textAlign: "center", marginTop: "50px" }}>
      <h1>Dark Mode in Next.js 🌙</h1>
      <button
        onClick={toggleDarkMode}
        style={{
          padding: "10px 20px",
          fontSize: "18px",
          cursor: "pointer",
          background: darkMode ? "#fff" : "#333",
          color: darkMode ? "#000" : "#fff",
          border: "none",
          borderRadius: "5px",
        }}
      >
        {darkMode ? "Switch to Light Mode ☀️" : "Switch to Dark Mode 🌙"}
      </button>
    </div>
  );
}

✅ ข้อดี:

  • จำค่าธีมได้หลังจากรีเฟรช


🎨 3. ใช้ next-themes (แนะนำ!)

✅ ข้อดีของ next-themes

  • ใช้ง่ายมาก (ไม่ต้องเขียนโค้ดเยอะ)
  • รองรับ ระบบ Dark Mode อัตโนมัติจาก OS



🛠 ติดตั้ง next-themes

npm install next-themes


👨‍💻 ใช้งาน next-themes

1️⃣ แก้ไข _app.js

import { ThemeProvider } from "next-themes";

export default function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider attribute="class">
      <Component {...pageProps} />
    </ThemeProvider>
  );
}

2️⃣ แก้ไข index.js

import { useTheme } from "next-themes";
import { useEffect, useState } from "react";

export default function Home() {
  const { theme, setTheme } = useTheme();
  const [mounted, setMounted] = useState(false);

  useEffect(() => setMounted(true), []);

  if (!mounted) return null; // ป้องกัน Hydration Error

  return (
    <div className="p-5 text-center">
      <h1 className="text-2xl">Dark Mode with next-themes 🌙</h1>
      <button
        onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
        className="mt-3 px-4 py-2 text-white bg-black rounded"
      >
        {theme === "dark" ? "Switch to Light Mode ☀️" : "Switch to Dark Mode 🌙"}
      </button>
    </div>
  );
}

🔥 ง่ายสุดๆ แค่เรียก setTheme() แล้วปล่อยให้ next-themes จัดการให้!

🏁 สรุป

วิธี ข้อดี ข้อเสีย
CSS Variables + useState ง่าย, ไม่ต้องใช้ไลบรารี รีเฟรชแล้วค่าหาย
localStorage จำค่าธีมได้หลังรีเฟรช ต้องใช้ useEffect
next-themes (แนะนำ) รองรับ Dark Mode อัตโนมัติ ต้องติดตั้งไลบรารี

🎯 ถ้าคุณอยากทำ Dark Mode แบบง่ายสุด 👉 ใช้ next-themes
🎯 ถ้าอยากควบคุมเองทั้งหมด 👉 ใช้ CSS Variables + localStorage

🚀 ลองทำเลย แล้วเว็บของคุณจะดูโปรขึ้น 300%!! 😆

วันอาทิตย์ที่ 23 กุมภาพันธ์ พ.ศ. 2568

การใช้ Tailwind CSS กับ Next.js แบบเข้าใจง่าย

Tailwind CSS เป็นหนึ่งใน CSS Framework ที่มาแรงที่สุดในตอนนี้ เพราะมันทำให้การเขียนสไตล์สะดวกขึ้นแบบสุด ๆ และใช้งานร่วมกับ Next.js ได้อย่างลงตัว วันนี้เราจะมาดูวิธีติดตั้งและใช้งาน Tailwind CSS กับ Next.js ตั้งแต่เริ่มต้นจนถึงเทคนิคการใช้งานให้โค้ดดูสะอาดขึ้น

🌟 ทำไมต้องใช้ Tailwind CSS?

Tailwind CSS ไม่เหมือน CSS Framework ทั่วไป เช่น Bootstrap ที่ให้เราสไตล์องค์ประกอบต่าง ๆ มาพร้อมใช้งานเลย แต่ Tailwind ใช้แนวคิด Utility-First หรือก็คือให้เรากำหนดสไตล์เองผ่าน class ที่เล็ก ๆ เช่น

<button class="bg-blue-500 text-white px-4 py-2 rounded">คลิกเลย!</button>

แปลว่าเราไม่ต้องสร้างไฟล์ CSS แยก ไม่ต้องคิดชื่อ class เอง แค่ใช้ class ที่มีมาให้ก็พอ! 🎉

🛠 วิธีติดตั้ง Tailwind CSS ใน Next.js

1. เปิด terminal แล้วรันคำสั่งติดตั้ง

npx create-next-app@latest my-tailwind-app
cd my-tailwind-app

2. ติดตั้ง Tailwind CSS และแพ็กเกจที่เกี่ยวข้อง

npm install -D tailwindcss postcss autoprefixer

3. สร้างไฟล์ tailwind.config.js

npx tailwindcss init -p

4. แก้ไข tailwind.config.js เพื่อให้ Tailwind ทำงานกับไฟล์ Next.js

module.exports = {
  content: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};

5. นำเข้า Tailwind CSS ในไฟล์ styles/globals.css

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

6. ลองรันเซิร์ฟเวอร์ดู! 🚀

    npm run dev


🎨 เริ่มใช้งาน Tailwind CSS ใน Next.js

ตัวอย่างการใช้งานเบื้องต้น

เปิด pages/index.js แล้วลองใช้ Tailwind CSS

export default function Home() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100">
      <h1 className="text-4xl font-bold text-blue-600">สวัสดี Tailwind CSS + Next.js!</h1>
    </div>
  );
}

🔥 สไตล์ที่ใช้ไปมีอะไรบ้าง?

  • min-h-screen → ให้ความสูงเต็มหน้าจอ
  • flex items-center justify-center → จัดให้อยู่ตรงกลาง
  • bg-gray-100 → พื้นหลังสีเทาอ่อน
  • text-4xl → ขนาดตัวอักษรใหญ่
  • font-bold → ตัวหนา
  • text-blue-600 → สีตัวอักษรฟ้า

ง่ายและเร็วมาก! 😍


🛠 เทคนิคการใช้งาน Tailwind CSS ให้โค้ดสะอาดขึ้น

✨ ใช้ @apply ในไฟล์ CSS

ถ้า class มันเยอะไป เราสามารถใช้ @apply เพื่อรวม class ใน globals.css ได้

/* styles/globals.css */
.btn {
  @apply bg-blue-500 text-white px-4 py-2 rounded shadow-md hover:bg-blue-600;
}

แล้วใช้ใน JSX แบบนี้

<button className="btn">กดเลย!</button>


📌 ใช้ classnames เพื่อจัดการ class ที่ซับซ้อน

ถ้ามีเงื่อนไขว่า class ไหนต้องแสดงหรือไม่แสดง ลองใช้ไลบรารี classnames

npm install classnames

จากนั้นใช้แบบนี้

import classNames from "classnames";

function Button({ primary }) {
  return (
    <button
      className={classNames(
        "px-4 py-2 rounded",
        primary ? "bg-blue-500 text-white" : "bg-gray-300 text-black"
      )}
    >
      กดเลย!
    </button>
  );
}

⚡️ ใช้ Tailwind CSS กับ Components ใน Next.js

สร้างคอมโพเนนต์ปุ่ม

สร้างไฟล์ components/Button.js

export default function Button({ children }) {
  return (
    <button className="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">
      {children}
    </button>
  );
}

แล้วใช้ใน index.js

import Button from "../components/Button";

export default function Home() {
  return (
    <div className="min-h-screen flex items-center justify-center">
      <Button>คลิกฉัน!</Button>
    </div>
  );
}

🚀 ใช้ Tailwind CSS กับ Dark Mode

Tailwind รองรับ Dark Mode ได้ง่ายมาก แค่เพิ่ม dark: ข้างหน้าคลาส

<div className="bg-white dark:bg-gray-800 text-black dark:text-white">
  โหมดมืดจ้า!
</div>

แต่ต้องไปแก้ tailwind.config.js นิดหน่อย

module.exports = {
  darkMode: "class", // เปิดใช้ dark mode แบบ manual
  content: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};

แล้วใช้ JavaScript เปลี่ยนโหมด

import { useEffect, useState } from "react";

export default function Home() {
  const [darkMode, setDarkMode] = useState(false);

  useEffect(() => {
    document.documentElement.classList.toggle("dark", darkMode);
  }, [darkMode]);

  return (
    <div className="min-h-screen flex flex-col items-center justify-center">
      <button onClick={() => setDarkMode(!darkMode)} className="px-4 py-2 bg-blue-500 text-white rounded">
        เปลี่ยนโหมด
      </button>
    </div>
  );
}

🎯 Tailwind CSS กับ Next.js ทำอะไรได้อีก?

  • ใช้ Animations & Transitions เช่น animate-bounce
  • ใช้ Responsive Design ง่าย ๆ เช่น md:bg-red-500
  • ใช้ Grid & Flexbox ได้แบบสะดวกสุด ๆ
  • ใช้ Custom Theme ปรับแต่งสีหรือฟอนต์ใน tailwind.config.js


🔥 สรุป

  • Tailwind CSS ใช้งานง่ายและเร็วมากใน Next.js
  • ติดตั้งง่ายแค่ npm install tailwindcss
  • ใช้ class utility ได้เลย ไม่ต้องเขียน CSS แยก
  • ปรับแต่งธีมเองได้ และรองรับ Dark Mode
  • ใช้ร่วมกับ classnames หรือ @apply ให้โค้ดสะอาดขึ้น

ถ้าคุณยังไม่เคยลอง Tailwind CSS กับ Next.js นี่เป็นเวลาที่เหมาะสุด ๆ แล้ว! 🚀

การใช้ Image Optimization ใน Next.js: โหลดไว SEO ดี ประหยัดแบนด์วิธ!

เคยเจอปัญหาเว็บโหลดช้าเพราะรูปภาพขนาดใหญ่หรือเปล่า? 📷 ถ้าใช่ Next.js มีฟีเจอร์ Image Optimization ที่ช่วยให้รูปภาพโหลดเร็วขึ้น อัตโนมัติ ไม...