กลับไปหน้าหลัก

บทที่ 2: Theme และ Styling

เรียนรู้การปรับแต่ง Theme และใช้ sx prop เพื่อสร้าง UI ที่สวยงาม! 🎨
Theme Customization
sx prop
Color Palette
Typography
🤔 Theme คืออะไร? (อธิบายแบบง่ายๆ)

ลองนึกภาพว่าคุณเป็น นักออกแบบภายใน:

• 🎨 Theme: เหมือนแผนผังสีและลวดลายของห้อง

• 🪑 Components: เหมือนเฟอร์นิเจอร์ที่จะใช้สีตาม theme

• 🔧 sx prop: เหมือนการปรับแต่งเฟอร์นิเจอร์แต่ละชิ้น

• ✨ ผลลัพธ์: ห้องที่สวยงาม สีสันกลมกลืน และเปลี่ยนได้ง่าย

🎯 เมื่อเรียนจบบทนี้ คุณจะสามารถ:
  • สร้างและปรับแต่ง Theme

    กำหนดสี, typography, spacing

  • ใช้ sx prop อย่างมั่นใจ

    styling ที่เชื่อมต่อกับ theme

  • ทำ Responsive Design

    ใช้ breakpoints ในการออกแบบ

  • Color Palette แบบมืออาชีพ

    primary, secondary, และสีอื่นๆ

  • Typography Hierarchy

    ระบบตัวอักษรที่สวยงาม

  • Component Customization

    ปรับแต่ง component แต่ละตัว

🎨 Theme พื้นฐาน

Theme ใน MUI เป็นวิธีกำหนดลักษณะของ UI ทั้งแอป รวมถึงสี ตัวอักษร และ spacing

🔧 แนวคิดสำคัญ
Theme Provider

ตัวหลักที่ wrap แอปทั้งหมด ให้ theme ใช้งานได้ทุกที่

💻 ตัวอย่างโค้ด:
import { ThemeProvider, createTheme } from '@mui/material/styles';

const theme = createTheme({
  palette: {
    primary: { main: '#1976d2' }
  }
});

<ThemeProvider theme={theme}>
  <App />
</ThemeProvider>
Palette (สี)

กำหนดสีหลักของแอป ทั้ง primary, secondary, error, warning, info, success

💻 ตัวอย่างโค้ด:
const theme = createTheme({
  palette: {
    primary: { main: '#1976d2' },    // สีหลัก
    secondary: { main: '#dc004e' },  // สีรอง
    error: { main: '#d32f2f' },      // สีแจ้งเตือน
    warning: { main: '#ed6c02' },    // สีเตือน
    info: { main: '#0288d1' },       // สีข้อมูล
    success: { main: '#2e7d32' },    // สีสำเร็จ
  },
});
Typography

กำหนดรูปแบบตัวอักษร ขนาด weight และ font family

💻 ตัวอย่างโค้ด:
const theme = createTheme({
  typography: {
    fontFamily: 'Roboto, Arial, sans-serif',
    h1: {
      fontSize: '2.5rem',
      fontWeight: 600,
    },
    h2: {
      fontSize: '2rem',
      fontWeight: 500,
    },
    body1: {
      fontSize: '1rem',
      lineHeight: 1.6,
    },
  },
});