Skip to content

Attribute Binding ใน React: เข้าใจและใช้งานอย่างถูกต้อง

การ binding attribute ใน React คือการกำหนดค่าต่างๆ ให้กับ HTML attribute ผ่าน JSX ซึ่งช่วยให้เราสามารถใช้ค่าคงที่หรือค่าที่มาจากตัวแปร/props/state ได้อย่างยืดหยุ่น


1. การกำหนด attribute แบบพื้นฐาน

ใน React เราใช้ JSX ซึ่งหน้าตาคล้าย HTML แต่จะมีความแตกต่างบางอย่าง เช่น การใช้ className แทน class, htmlFor แทน for เป็นต้น

jsx
function MyButton() {
  return <button className="primary-btn">Click me!</button>;
}

2. การ binding ค่าจากตัวแปร

เราสามารถใช้ JavaScript expression ใน JSX ได้ โดยต้องใส่ไว้ใน {}

jsx
const isActive = true;
return <button disabled={!isActive}>Submit</button>;

อธิบาย: ถ้า isActive เป็น true ปุ่มจะไม่ถูก disable ถ้าเป็น false ปุ่มจะถูก disable


3. การ binding ค่าจาก props หรือ state

jsx
function UserAvatar({ src, alt }) {
  return <img src={src} alt={alt} width={100} />;
}

อธิบาย: ค่าของ src และ alt ถูก binding มาจาก props ที่ส่งเข้ามา


4. การกำหนด attribute แบบ dynamic

สามารถใช้ ternary operator หรือ expression อื่นๆ ได้

jsx
const isError = true;
return (
  <span style={{ color: isError ? "red" : "green" }}>
    {isError ? "ผิดพลาด" : "สำเร็จ"}
  </span>
);

5. ข้อควรระวัง

  • ชื่อ attribute ต้องใช้แบบ camelCase เช่น tabIndex, readOnly
  • หลีกเลี่ยงการใส่ค่าที่ไม่จำเป็น เช่น <input disabled={false} /> จะไม่ disable input
  • ถ้า attribute เป็น boolean เช่น checked, disabled ให้ส่งค่าจากตัวแปรได้เลย
  • ถ้าต้องการกำหนด style หลายค่า ให้ใช้ object แบบนี้
jsx
const styleObj = { color: "blue", fontWeight: "bold" };
return <div style={styleObj}>ข้อความ</div>;

สรุป

Attribute binding ใน React ช่วยให้เราควบคุมการแสดงผลของ UI ได้อย่างยืดหยุ่นและปลอดภัย โดยอาศัยพลังของ JavaScript และแนวคิด declarative ของ React