Skip to content

Basic List Rendering

การเรนเดอร์รายการพื้นฐานที่มีรายการที่เรียบง่ายโดยไม่มีคุณสมบัติเพิ่มเติม

List with Objects

การเรนเดอร์รายการที่แต่ละรายการเป็นวัตถุที่มี id และ name คุณสมบัติ

List with Conditional Rendering

การเรนเดอร์รายการที่แสดงเฉพาะรายการที่มีสถานะพร้อมใช้งาน

jsx
import React from 'react';

const items = [
  { id: 1, name: 'Apple', available: true },
  { id: 2, name: 'Banana', available: false },
  { id: 3, name: 'Cherry', available: true }
];

export default function ItemList() {
  return (
    <ul>
      {items.map(item => (
        item.available && <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

List with Custom Components

การเรนเดอร์รายการโดยใช้คอมโพเนนต์ Item ที่กำหนดเองสำหรับแต่ละรายการในรายการ

jsx
import React from 'react';

const Item = ({ name }) => <li>{name}</li>;

const items = ['Apple', 'Banana', 'Cherry'];

export default function ItemList() {
  return (
    <ul>
      {items.map((item, index) => (
        <Item key={index} name={item} />
      ))}
    </ul>
  );
}

Dynamic List with State

การเรนเดอร์รายการที่สามารถเพิ่มรายการใหม่ได้ตามการโต้ตอบของผู้ใช้

jsx
import React, { useState } from 'react';

export default function ItemList() {
  const [items, setItems] = useState(['Apple', 'Banana', 'Cherry']);

  const addItem = () => {
    setItems([...items, 'New Item']);
  };

  return (
    <div>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      <button onClick={addItem}>Add Item</button>
    </div>
  );
}

List with Inline Styles

การเรนเดอร์รายการที่ใช้สไตล์ในบรรทัดสำหรับแต่ละรายการ

jsx
import React from 'react';

const items = ['Apple', 'Banana', 'Cherry'];

const listItemStyle = {
  color: 'blue',
  fontSize: '20px'
};

export default function ItemList() {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index} style={listItemStyle}>{item}</li>
      ))}
    </ul>
  );
}

List with Class Names

การเรนเดอร์รายการที่ใช้ชื่อคลาส CSS สำหรับแต่ละรายการ

jsx
import React from 'react';
import './ItemList.css'; // Assuming you have some CSS styles defined here

const items = ['Apple', 'Banana', 'Cherry'];

export default function ItemList() {
  return (
    <ul className="item-list">
      {items.map((item, index) => (
        <li key={index} className="item">{item}</li>
      ))}
    </ul>
  );
}

ItemList.css:

css
.item-list {
  list-style-type: none;
  padding: 0;
}

.item {
  color: green;
  font-size: 18px;
}

List with Nested Components

การเรนเดอร์รายการที่แต่ละรายการถูกแทนด้วยคอมโพเนนต์ที่ซ้อนกัน

jsx
import React from 'react';

const Item = ({ name }) => (
  <div>
    <h3>{name}</h3>
  </div>
);

const items = ['Apple', 'Banana', 'Cherry'];

export default function ItemList() {
  return (
    <div>
      {items.map((item, index) => (
        <Item key={index} name={item} />
      ))}
    </div>
  );
}

Released under the MIT License