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

วันพุธที่ 2 เมษายน พ.ศ. 2568

การสร้าง Dashboard UI ใน Next.js: ทำง่าย ใช้งานจริง แบบโปรๆ

เคยไหม? เวลาจะสร้าง Dashboard สวยๆ ในเว็บแอปพลิเคชันแต่ไม่รู้จะเริ่มตรงไหน? วันนี้เราจะมาลุยกันว่า Next.js จะช่วยให้เราสร้าง Dashboard UI ที่สวยงาม ใช้งานได้จริง และมีประสิทธิภาพได้ยังไง

🔥 ทำไมต้องใช้ Next.js สำหรับ Dashboard?

Next.js เป็นหนึ่งใน React Framework ที่เหมาะกับการสร้าง Dashboard มากๆ เพราะมันมีฟีเจอร์ที่ช่วยให้การพัฒนาเร็วขึ้น เช่น

✅ Server-side Rendering (SSR) – โหลดข้อมูลแบบเร็วจี๋ 🚀
✅ Static Site Generation (SSG) – ลดโหลดเซิร์ฟเวอร์และเพิ่มความเร็ว
✅ API Routes – จัดการข้อมูลจาก Backend ได้ในตัว
✅ การรองรับ Tailwind CSS, MUI, Ant Design – ทำ UI ได้ง่ายขึ้น

🛠️ เริ่มต้นโปรเจกต์ Dashboard ด้วย Next.js

1️⃣ ติดตั้ง Next.js

ถ้ายังไม่มีโปรเจกต์ Next.js ให้สร้างใหม่ก่อน

npx create-next-app@latest my-dashboard
cd my-dashboard
npm install

หรือถ้าใช้ Yarn

yarn create next-app my-dashboard
cd my-dashboard
yarn install

2️⃣ ติดตั้ง UI Library (Tailwind CSS หรือ MUI)

เราจะใช้ Tailwind CSS เพราะมันเบาและทำให้ดีไซน์ง่าย

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

แล้วเพิ่ม Tailwind ลงในไฟล์ tailwind.config.js

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

จากนั้นใส่ Tailwind ลงใน styles/globals.css

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


🎨 สร้าง Layout หลักของ Dashboard

ปกติ Dashboard จะมี

✅ Sidebar
✅ Navbar
✅ Content Area

เราจะสร้าง Layout หลักที่ใช้ทั่วแอป

1️⃣ สร้างไฟล์ components/Layout.js

import Sidebar from './Sidebar';
import Navbar from './Navbar';

export default function Layout({ children }) {
  return (
    <div className="flex h-screen">
      <Sidebar />
      <div className="flex flex-col flex-1">
        <Navbar />
        <main className="p-4">{children}</main>
      </div>
    </div>
  );
}

2️⃣ สร้าง Sidebar (components/Sidebar.js)

import Link from 'next/link';

export default function Sidebar() {
  return (
    <div className="w-64 bg-gray-800 text-white h-screen p-5">
      <h2 className="text-xl font-bold mb-5">Dashboard</h2>
      <ul>
        <li className="mb-2">
          <Link href="/" className="block p-2 hover:bg-gray-700 rounded">🏠 หน้าหลัก</Link>
        </li>
        <li className="mb-2">
          <Link href="/analytics" className="block p-2 hover:bg-gray-700 rounded">📊 Analytics</Link>
        </li>
        <li className="mb-2">
          <Link href="/settings" className="block p-2 hover:bg-gray-700 rounded">⚙️ Settings</Link>
        </li>
      </ul>
    </div>
  );
}

3️⃣ สร้าง Navbar (components/Navbar.js)

export default function Navbar() {
  return (
    <div className="bg-white shadow-md p-4 flex justify-between">
      <h1 className="text-lg font-bold">Dashboard</h1>
      <div>👤 User</div>
    </div>
  );
}


4️⃣ ใช้ Layout ในหน้า pages/_app.js

import Layout from '../components/Layout';
import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}

export default MyApp;


📊 สร้างหน้า Dashboard พร้อมกราฟ

ใน Dashboard จริงๆ มักจะมี กราฟ และ ตารางข้อมูล เราจะใช้ Recharts เพื่อแสดงกราฟ

1️⃣ ติดตั้ง Recharts

npm install recharts


2️⃣ สร้างหน้า pages/index.js

import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';

const data = [
  { month: 'Jan', sales: 4000 },
  { month: 'Feb', sales: 3000 },
  { month: 'Mar', sales: 5000 },
  { month: 'Apr', sales: 7000 },
];

export default function Dashboard() {
  return (
    <div>
      <h1 className="text-2xl font-bold mb-4">📈 สถิติยอดขาย</h1>
      <div className="bg-white p-4 shadow-md">
        <ResponsiveContainer width="100%" height={300}>
          <LineChart data={data}>
            <XAxis dataKey="month" />
            <YAxis />
            <Tooltip />
            <Line type="monotone" dataKey="sales" stroke="#8884d8" strokeWidth={2} />
          </LineChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}


📌 เพิ่มตารางข้อมูล

เราจะใช้ TanStack Table เพื่อแสดงข้อมูลในรูปแบบตาราง

1️⃣ ติดตั้ง TanStack Table

npm install @tanstack/react-table

2️⃣ เพิ่มตารางใน pages/index.js

import { useReactTable, getCoreRowModel, flexRender } from '@tanstack/react-table';

const data = [
  { id: 1, name: 'John Doe', role: 'Admin' },
  { id: 2, name: 'Jane Smith', role: 'Editor' },
];

const columns = [
  { accessorKey: 'id', header: 'ID' },
  { accessorKey: 'name', header: 'ชื่อ' },
  { accessorKey: 'role', header: 'บทบาท' },
];

export default function Dashboard() {
  const table = useReactTable({ data, columns, getCoreRowModel: getCoreRowModel() });

  return (
    <div>
      <h1 className="text-2xl font-bold mb-4">👥 ผู้ใช้งาน</h1>
      <table className="border-collapse border border-gray-300 w-full">
        <thead>
          {table.getHeaderGroups().map((headerGroup) => (
            <tr key={headerGroup.id}>
              {headerGroup.headers.map((header) => (
                <th key={header.id} className="border p-2 bg-gray-100">
                  {flexRender(header.column.columnDef.header, header.getContext())}
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody>
          {table.getRowModel().rows.map((row) => (
            <tr key={row.id}>
              {row.getVisibleCells().map((cell) => (
                <td key={cell.id} className="border p-2">
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

🎯 สรุป

✅ สร้าง Dashboard UI ใน Next.js ได้ง่าย
✅ ใช้ Tailwind CSS ทำให้ UI สวยแบบไม่ต้องเขียน CSS เอง
✅ ใช้ Recharts และ TanStack Table เพื่อแสดงข้อมูลได้อย่างมืออาชีพ

พร้อมสร้าง Dashboard ของคุณเองแล้วหรือยัง?

วันอังคารที่ 1 เมษายน พ.ศ. 2568

การแสดงผลตารางใน Next.js ด้วย TanStack Table: ง่าย สวย และยืดหยุ่นสุดๆ

ถ้าคุณเคยต้องทำตารางใน React หรือ Next.js แล้วรู้สึกว่ามันยุ่งยากไปหมด ไม่ว่าจะเป็นการจัดการข้อมูล การกรอง (filtering) การเรียงลำดับ (sorting) หรือการแบ่งหน้า (pagination) วันนี้เราจะมาแนะนำ TanStack Table (หรือชื่อเดิมคือ React Table) ที่จะช่วยให้คุณสร้างตารางขั้นเทพได้แบบง่ายๆ

ทำไมต้องใช้ TanStack Table?

ในโปรเจกต์ที่ต้องแสดงข้อมูลในรูปแบบตาราง เช่น รายการคำสั่งซื้อ, รายการผู้ใช้ หรือข้อมูลสถิติต่างๆ เราต้องการฟีเจอร์พวกนี้:

✅ การจัดการข้อมูลที่ยืดหยุ่น (เช่น ใช้ API ดึงข้อมูลมาแสดง)
✅ Sorting, Filtering, และ Pagination แบบไม่ต้องเขียนเอง
✅ รองรับการใช้งานกับ Next.js และ SSR (Server-side Rendering)

TanStack Table ทำได้หมด! 🎉

ติดตั้ง TanStack Table

ก่อนอื่น เราต้องติดตั้งไลบรารีก่อน

npm install @tanstack/react-table

หรือถ้าใช้ Yarn

yarn add @tanstack/react-table


ตัวอย่างการใช้งานพื้นฐาน

มาลองสร้างตารางง่ายๆ กันก่อน โดยใช้ข้อมูลแบบ static

1. ตั้งค่าข้อมูลและคอลัมน์

const data = [
  { id: 1, name: 'John Doe', age: 28, email: 'john@example.com' },
  { id: 2, name: 'Jane Smith', age: 32, email: 'jane@example.com' },
  { id: 3, name: 'Bob Brown', age: 24, email: 'bob@example.com' },
];

const columns = [
  { accessorKey: 'id', header: 'ID' },
  { accessorKey: 'name', header: 'ชื่อ' },
  { accessorKey: 'age', header: 'อายุ' },
  { accessorKey: 'email', header: 'อีเมล' },
];

อธิบาย:

  • data คือข้อมูลที่เราจะเอามาแสดง
  • columns กำหนดโครงสร้างของตาราง ใช้ accessorKey เพื่อระบุคีย์ของข้อมูล


2. ใช้ TanStack Table เพื่อแสดงตาราง

import { useReactTable, getCoreRowModel, flexRender } from '@tanstack/react-table';

export default function MyTable() {
  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    <table border="1">
      <thead>
        {table.getHeaderGroups().map((headerGroup) => (
          <tr key={headerGroup.id}>
            {headerGroup.headers.map((header) => (
              <th key={header.id}>{flexRender(header.column.columnDef.header, header.getContext())}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody>
        {table.getRowModel().rows.map((row) => (
          <tr key={row.id}>
            {row.getVisibleCells().map((cell) => (
              <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

สรุปโค้ด:

  • useReactTable() ใช้สร้างตารางจาก data และ columns
  • getCoreRowModel() ใช้เพื่อจัดการโครงสร้างของข้อมูล
  • flexRender() ช่วยให้เราสามารถเรนเดอร์ค่าที่กำหนดใน columns ได้


เพิ่ม Sorting (เรียงลำดับ)

ถ้าอยากให้ตารางสามารถเรียงลำดับ (sorting) ได้ ให้เพิ่ม getSortedRowModel()

import { useReactTable, getCoreRowModel, getSortedRowModel, flexRender } from '@tanstack/react-table';

export default function MyTable() {
  const [sorting, setSorting] = React.useState([]);
 
  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    onSortingChange: setSorting,
    state: { sorting },
  });

  return (
    <table border="1">
      <thead>
        {table.getHeaderGroups().map((headerGroup) => (
          <tr key={headerGroup.id}>
            {headerGroup.headers.map((header) => (
              <th key={header.id} onClick={() => header.column.getToggleSortingHandler()?.()}>
                {flexRender(header.column.columnDef.header, header.getContext())}
                {header.column.getIsSorted() === 'asc' ? ' 🔼' : header.column.getIsSorted() === 'desc' ? ' 🔽' : ''}
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody>
        {table.getRowModel().rows.map((row) => (
          <tr key={row.id}>
            {row.getVisibleCells().map((cell) => (
              <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

ตอนนี้เราสามารถคลิกที่หัวตารางเพื่อเรียงข้อมูลได้แล้ว! 🎉


เพิ่ม Pagination (แบ่งหน้า)

ถ้าข้อมูลเยอะๆ เราอาจต้องการ pagination เพื่อให้ผู้ใช้สามารถเลื่อนดูหน้าอื่นๆ ได้

import { useReactTable, getCoreRowModel, getPaginationRowModel, flexRender } from '@tanstack/react-table';

export default function MyTable() {
  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
  });

  return (
    <div>
      <table border="1">
        <thead>
          {table.getHeaderGroups().map((headerGroup) => (
            <tr key={headerGroup.id}>
              {headerGroup.headers.map((header) => (
                <th key={header.id}>{flexRender(header.column.columnDef.header, header.getContext())}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody>
          {table.getRowModel().rows.map((row) => (
            <tr key={row.id}>
              {row.getVisibleCells().map((cell) => (
                <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
      <div>
        <button onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()}>
          ก่อนหน้า
        </button>
        <span> หน้า {table.getState().pagination.pageIndex + 1} </span>
        <button onClick={() => table.nextPage()} disabled={!table.getCanNextPage()}>
          ถัดไป
        </button>
      </div>
    </div>
  );
}


สรุป

✅ TanStack Table ช่วยให้สร้างตารางใน Next.js ได้ง่ายและยืดหยุ่น
✅ รองรับ Sorting, Pagination, Filtering
✅ ทำงานได้ดีทั้ง Client-side และ Server-side Rendering

ถ้าคุณต้องการตารางที่เร็วและยืดหยุ่น TanStack Table คือตัวเลือกที่ดีสุด! 

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

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