본문으로 건너뛰기

เนื้อหาภาษาไทย / 태국어 콘텐츠

시스템 가이드 검수 완료된 콘텐츠

การปรับแต่ง Theme และ Style ใน Material UI

บทความนี้กล่าวถึงการปรับแต่ง Theme และ Style ใน Material UI เพื่อให้ Component ต่างๆ เข้ากับ Design System ของโปรเจกต์ โดยเน้นที่การสร้าง Custom Theme ด้วย `cre...

การปรับแต่ง Theme และ Style ใน Material UI

หลังจากที่เราได้รู้จักกับ Material UI และวิธีการติดตั้งใช้งานในโปรเจกต์ React แล้ว ในบทนี้เราจะมาเรียนรู้ถึงวิธีการปรับแต่ง Theme และ Style เพื่อให้ Component ต่างๆ ของ Material UI เข้ากับ Design System ของเรามากขึ้น ซึ่งเป็นหัวใจสำคัญของการสร้าง UI ที่สวยงามและสอดคล้องกันทั้งโปรเจกต์

ทำไมต้องปรับแต่ง Theme และ Style?

Material UI มาพร้อมกับ Theme Default ที่สวยงามและใช้งานได้ดี แต่ในหลายๆ ครั้ง เราต้องการปรับเปลี่ยนสี, Typography (ฟอนต์และขนาด), Spacing (ระยะห่าง) หรือแม้แต่รูปทรงของ Component ให้เข้ากับ Brand Identity ของเรา หรือเพื่อให้สอดคล้องกับ Design System ที่เราวางแผนไว้ การปรับแต่ง Theme และ Style ช่วยให้เรา:

  • สร้าง UI ที่มีเอกลักษณ์และแตกต่างจาก UI ทั่วไปที่ใช้ Material UI
  • ควบคุม Style ของ Component ทั้งโปรเจกต์ได้อย่างเป็นระบบ
  • ลดความซ้ำซ้อนในการเขียน CSS
  • เพิ่มความสอดคล้องและความเป็นอันหนึ่งอันเดียวกันของ UI

การสร้าง Custom Theme

Material UI อนุญาตให้เราสร้าง Custom Theme เพื่อกำหนดค่าต่างๆ ที่จะถูกนำไปใช้กับ Component ทั้งหมดในโปรเจกต์ของเรา วิธีการสร้าง Custom Theme ทำได้โดยใช้ฟังก์ชัน createTheme จาก @mui/material/styles

import { createTheme } from '@mui/material/styles';

const theme = createTheme({
  palette: {
    primary: {
      main: '#FF5733', // สีหลักของแบรนด์
    },
    secondary: {
      main: '#33FF57', // สีรองของแบรนด์
    },
  },
  typography: {
    fontFamily: 'Kanit, sans-serif', // ฟอนต์หลักของแบรนด์
    h1: {
      fontSize: '3rem',
      fontWeight: 700,
    },
  },
});

export default theme;

ในตัวอย่างนี้ เราได้สร้าง Theme ใหม่โดยกำหนดค่า palette (ชุดสี) และ typography (การจัดรูปแบบตัวอักษร) โดย:

  • palette.primary.main กำหนดสีหลักของแบรนด์ (ในที่นี้คือสีส้ม #FF5733)
  • palette.secondary.main กำหนดสีรองของแบรนด์ (ในที่นี้คือสีเขียว #33FF57)
  • typography.fontFamily กำหนดฟอนต์หลักของแบรนด์ (ในที่นี้คือฟอนต์ Kanit)
  • typography.h1 กำหนด Style สำหรับ Heading ระดับ 1 (H1) โดยกำหนดขนาดและน้ำหนักของฟอนต์

ข้อผิดพลาดที่พบบ่อย: การลืม import ฟอนต์ที่กำหนดไว้ใน typography.fontFamily ทำให้ Component แสดงผลด้วยฟอนต์ Default ของ Browser ดังนั้นอย่าลืม import ฟอนต์จาก Google Fonts หรือแหล่งอื่นๆ ก่อนใช้งาน

การใช้ ThemeProvider

เมื่อเราสร้าง Custom Theme แล้ว เราต้องทำการ "ห่อ" Component ทั้งหมดในโปรเจกต์ของเราด้วย ThemeProvider จาก @mui/material/styles เพื่อให้ Component เหล่านั้นสามารถเข้าถึง Theme ที่เรากำหนดได้

import React from 'react';
import { ThemeProvider } from '@mui/material/styles';
import theme from './theme'; // import theme ที่เราสร้างไว้
import App from './App';

function Root() {
  return (
    <ThemeProvider theme={theme}>
      <App />
    </ThemeProvider>
  );
}

export default Root;

ในตัวอย่างนี้ เราได้ import Theme ที่เราสร้างไว้ และนำมาใส่ใน ThemeProvider ที่ห่อ Component App ไว้ ทำให้ Component ทั้งหมดภายใน App สามารถเข้าถึงและใช้ค่าต่างๆ ใน Theme ได้

กรณีใช้งานจริง: โดยทั่วไปเราจะ Wrap ThemeProvider ไว้ที่ Root Component ของ Application ของเรา เช่น ใน index.js หรือ App.js

การปรับแต่งสีและ Typography

อย่างที่กล่าวไปข้างต้น เราสามารถปรับแต่งสีและ Typography ได้อย่างละเอียดใน Custom Theme โดย Material UI มี Properties ให้เราปรับแต่งมากมาย เช่น:

  • Palette: ใช้สำหรับกำหนดชุดสีต่างๆ เช่น primary, secondary, error, warning, info, success รวมถึง background และ text
  • Typography: ใช้สำหรับกำหนด Style ของ Text ต่างๆ เช่น fontFamily, fontSize, fontWeight, lineHeight และ Style สำหรับ Heading ต่างๆ (h1, h2, h3, ...) และ Body Text (body1, body2)

ตัวอย่างการปรับแต่งสีเพิ่มเติม:

const theme = createTheme({
  palette: {
    primary: {
      main: '#FF5733',
      light: '#FF8A65',
      dark: '#E64A19',
      contrastText: '#fff', // สีตัวอักษรเมื่ออยู่บนพื้นสี primary
    },
    secondary: {
      main: '#33FF57',
      light: '#69FF84',
      dark: '#14E63A',
      contrastText: '#000', // สีตัวอักษรเมื่ออยู่บนพื้นสี secondary
    },
    error: {
      main: '#F44336',
    },
  },
});

ในตัวอย่างนี้ เราได้เพิ่ม Properties light, dark, และ contrastText ให้กับ primary และ secondary ซึ่งช่วยให้เราสามารถใช้สีที่หลากหลายมากขึ้นใน Component ต่างๆ

ตัวอย่างการปรับแต่ง Typography เพิ่มเติม:

const theme = createTheme({
  typography: {
    fontFamily: 'Kanit, sans-serif',
    h1: {
      fontSize: '3rem',
      fontWeight: 700,
    },
    body1: {
      fontSize: '1rem',
      lineHeight: 1.5,
    },
  },
});

ในตัวอย่างนี้ เราได้กำหนด Style สำหรับ body1 ซึ่งเป็น Style Default สำหรับ Text ทั่วไป โดยกำหนดขนาดและระยะห่างบรรทัด

แนวคิดเชิงระบบ: การกำหนดค่าสีและ Typography ใน Theme ควรเป็นไปตาม Design Token ที่เรากำหนดไว้ใน Design System เพื่อให้มั่นใจได้ว่า UI ของเรามีความสอดคล้องกัน

การใช้ makeStyles และ withStyles

นอกจากการปรับแต่ง Theme แล้ว Material UI ยังมีเครื่องมือ makeStyles และ withStyles ที่ช่วยให้เราสามารถเขียน Style เฉพาะสำหรับ Component แต่ละตัวได้

makeStyles

makeStyles เป็น Hook ที่ใช้สำหรับสร้าง Style สำหรับ Function Component

import React from 'react';
import { makeStyles } from '@mui/styles';
import { Button } from '@mui/material';

const useStyles = makeStyles((theme) => ({
  root: {
    backgroundColor: theme.palette.primary.main,
    color: theme.palette.primary.contrastText,
    '&:hover': {
      backgroundColor: theme.palette.primary.dark,
    },
  },
}));

function MyButton() {
  const classes = useStyles();

  return (
    <Button className={classes.root}>
      My Button
    </Button>
  );
}

export default MyButton;

ในตัวอย่างนี้ เราได้สร้าง Hook useStyles โดยใช้ makeStyles ซึ่งรับ Function เป็น Argument Function นี้จะรับ theme เป็น Argument และ return Object ที่มี Style ต่างๆ ที่เราต้องการกำหนด

เราสามารถเข้าถึงค่าต่างๆ ใน Theme ได้โดยใช้ theme.palette, theme.typography, theme.spacing เป็นต้น

ข้อผิดพลาดที่พบบ่อย: การลืม import makeStyles จาก @mui/styles ทำให้เกิด Error ขึ้น

withStyles

withStyles เป็น Higher-Order Component (HOC) ที่ใช้สำหรับสร้าง Style สำหรับ Class Component

import React from 'react';
import { withStyles } from '@mui/styles';
import { Button } from '@mui/material';

const styles = (theme) => ({
  root: {
    backgroundColor: theme.palette.secondary.main,
    color: theme.palette.secondary.contrastText,
    '&:hover': {
      backgroundColor: theme.palette.secondary.dark,
    },
  },
});

class MyButton extends React.Component {
  render() {
    const { classes } = this.props;

    return (
      <Button className={classes.root}>
        My Button
      </Button>
    );
  }
}

export default withStyles(styles)(MyButton);

ในตัวอย่างนี้ เราได้สร้าง Style โดยใช้ withStyles ซึ่งรับ Function styles เป็น Argument Function นี้จะรับ theme เป็น Argument และ return Object ที่มี Style ต่างๆ ที่เราต้องการกำหนด

withStyles จะ Inject Property classes เข้าไปใน Component ของเรา ซึ่งเราสามารถใช้ classes.root เพื่อ Apply Style ที่เรากำหนดไว้ได้

ข้อควรระวัง: withStyles เหมาะสำหรับ Class Component แต่สำหรับ Function Component ควรใช้ makeStyles แทน

สรุป

การปรับแต่ง Theme และ Style ใน Material UI เป็นสิ่งสำคัญในการสร้าง UI ที่สวยงามและสอดคล้องกับ Design System ของเรา โดยเราสามารถสร้าง Custom Theme โดยใช้ createTheme และ ThemeProvider และปรับแต่ง Style ของ Component แต่ละตัวโดยใช้ makeStyles และ withStyles การเข้าใจและใช้งานเครื่องมือเหล่านี้จะช่วยให้เราสามารถควบคุม Style ของ Component ทั้งหมดในโปรเจกต์ได้อย่างมีประสิทธิภาพ และสร้าง UI ที่มีเอกลักษณ์และเป็นไปตามความต้องการของเรา

ในบทต่อไป เราจะมาเรียนรู้ถึงวิธีการสร้าง Component ที่ Reusable ด้วย Material UI ซึ่งจะช่วยให้เราสามารถนำ Component ที่เราสร้างไว้ไปใช้ซ้ำได้ในหลายๆ ที่ และลดความซ้ำซ้อนในการเขียน Code

Office.in.th Custom Service

이 구조를 바탕으로 시스템을 개발하거나 맞춤 변경하고 싶으신가요?

Office.in.th는 엔터프라이즈 웹 애플리케이션, API 연동, 공공/민간 업무 관리 시스템을 설계·개발하며 장기 지원을 제공합니다.

소프트웨어 개발 서비스 보기