Skip to content

Conditional Rendering ใน React

Conditional Rendering คืออะไร?

Conditional Rendering คือการแสดงผล UI ตามเงื่อนไขที่กำหนด เช่น แสดงหรือซ่อนคอมโพเนนต์ตามค่าของตัวแปร เหมือนกับ if/else ใน JavaScript แต่ใช้ใน JSX


วิธีการเขียนเงื่อนไขใน JSX

1. ใช้ if/else (นอก JSX)

tsx
let content;
if (isLoggedIn) {
  content = <p>Welcome!</p>;
} else {
  content = <p>Please login.</p>;
}
return <div>{content}</div>;

2. ใช้ ternary operator (นิยมสุด)

tsx
return (
  <div>
    {isLoggedIn ? <p>Welcome!</p> : <p>Please login.</p>}
  </div>
);

3. ใช้ && (short-circuit)

tsx
return (
  <div>
    {error && <p className="text-red">เกิดข้อผิดพลาด</p>}
  </div>
);

4. ใช้ function ช่วย

tsx
function renderStatus(status: string) {
  if (status === "loading") return <p>Loading...</p>;
  if (status === "error") return <p>Error!</p>;
  return <p>Done!</p>;
}

// ใน JSX
return <div>{renderStatus(status)}</div>;

ตัวอย่างการซ่อน/แสดงคอมโพเนนต์

tsx
function Profile({ user }: { user?: { name: string } }) {
  if (!user) return <p>กรุณาเข้าสู่ระบบ</p>;
  return <p>สวัสดี {user.name}</p>;
}

Best Practice

  • ใช้ ternary operator สำหรับกรณีง่ายๆ
  • ใช้ฟังก์ชันช่วยถ้าเงื่อนไขซับซ้อนหรือมีหลายกรณี
  • หลีกเลี่ยง if/else ใน JSX โดยตรง (อ่านยาก)

เปรียบเทียบกับแนวทางเก่า (Class Component)

tsx
class Profile extends React.Component<{ user?: { name: string } }> {
  render() {
    if (!this.props.user) return <p>กรุณาเข้าสู่ระบบ</p>;
    return <p>สวัสดี {this.props.user.name}</p>;
  }
}

ปัจจุบัน Function Component + JSX เงื่อนไขอ่านง่ายและกระชับกว่า


สรุปแนวทางที่แนะนำ

  • ใช้ Function Component + JSX + ternary/&& เป็นหลัก
  • ใช้ฟังก์ชันช่วยถ้าเงื่อนไขซับซ้อน
  • ฝึกแยก logic ออกจาก JSX เพื่อความอ่านง่าย

Conditional Rendering คือหัวใจของ UI ที่ตอบสนองสถานะต่างๆ ได้ดีใน React สมัยใหม่