Skip to content

การจัดการสไตล์ใน React

1. CSS-in-JS

CSS-in-JS ช่วยให้เขียน CSS ใน JavaScript โดยตรง มีข้อดีเรื่อง Scoped Styles และสามารถใช้ตัวแปรจาก JavaScript ได้

tsx
/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";

const buttonStyle = css`
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
`;

function Button() {
  return <button css={buttonStyle}>Click Me</button>;
}

2. CSS Modules

CSS Modules เป็นวิธีที่นิยมใช้ใน React โดยจะสร้าง unique class name ให้อัตโนมัติ ป้องกันการชนกันของชื่อคลาส

tsx
// Button.module.css
.primary {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
}

// Button.tsx
import styles from './Button.module.css';

function Button() {
  return <button className={styles.primary}>Click Me</button>;
}

3. Tailwind CSS

Tailwind CSS เป็น Utility-First CSS Framework ที่ช่วยให้สร้าง UI ได้รวดเร็วโดยไม่ต้องออกจากไฟล์ Component

tsx
function Button() {
  return (
    <button className="px-4 py-2 bg-blue-500 text-white rounded">
      Click Me
    </button>
  );
}

4. Styled Components

Styled Components เป็นไลบรารี CSS-in-JS ที่นิยม ช่วยสร้าง Component ที่มีสไตล์เป็นส่วนหนึ่งของ Component นั้น

tsx
import styled from "styled-components";

const StyledButton = styled.button`
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
`;

function Button() {
  return <StyledButton>Click Me</StyledButton>;
}

5. การใช้ CSS Variables

CSS Variables ช่วยจัดการค่าสไตล์ที่ใช้ร่วมกันได้ง่าย และสามารถเปลี่ยนแปลงค่าได้ใน runtime ผ่าน JavaScript

tsx
// styles.css
:root {
  --primary-color: #007bff;
}

// Button.tsx
function Button() {
  return (
    <button 
      style={{ 
        backgroundColor: 'var(--primary-color)' 
      }}
    >
      Click Me
    </button>
  );
}