← Về danh sách bài họcBài 4/25

📦 Bài 4: Props - Truyền Dữ Liệu Giữa Components

⏱️ Thời gian đọc: 12 phút | 📚 Độ khó: Dễ

🎯 Sau bài học này, bạn sẽ:

1. Props Là Gì?

Props (Properties) là cách truyền dữ liệu từ component cha xuống component con. Props là read-only — component con không được phép thay đổi props.

// Component nhận props
function Greeting({ name, age }) {
    return <p>{name}, {age} tuổi</p>;
}

// Truyền props
function App() {
    return (
        <div>
            <Greeting name="An" age={25} />
            <Greeting name="Bình" age={30} />
        </div>
    );
}

2. Các Loại Props

function Demo({
    text,           // String
    count,          // Number
    isActive,       // Boolean
    items,          // Array
    user,           // Object
    onClick,        // Function
    children        // Children (JSX bên trong tag)
}) {
    return (
        <div>
            <p>{text}</p>
            <p>Count: {count}</p>
            {isActive && <span>Active!</span>}
            <ul>{items.map((item, i) => <li key={i}>{item}</li>)}</ul>
            <p>User: {user.name}</p>
            <button onClick={onClick}>Click</button>
            <div>{children}</div>
        </div>
    );
}

// Sử dụng
<Demo
    text="Hello"
    count={42}
    isActive={true}
    items={['A', 'B', 'C']}
    user={{ name: 'An' }}
    onClick={() => alert('Clicked!')}
>
    <p>Đây là children prop</p>
</Demo>

3. Default Props

// Cách 1: Default parameter (khuyên dùng)
function Button({ text = 'Click me', color = 'blue', size = 'md' }) {
    return (
        <button style={{ background: color }} className={`btn-${size}`}>
            {text}
        </button>
    );
}

// Sử dụng
<Button />                    {/* text="Click me", color="blue" */}
<Button text="Submit" />      {/* text="Submit", color="blue" */}
<Button color="red" />        {/* text="Click me", color="red" */}

4. Children Prop

// Container component
function Card({ title, children }) {
    return (
        <div className="card">
            <div className="card-header">
                <h3>{title}</h3>
            </div>
            <div className="card-body">
                {children}
            </div>
        </div>
    );
}

// Sử dụng - bất kỳ JSX nào bên trong tag đều là children
<Card title="Thông tin user">
    <p>Tên: An</p>
    <p>Email: an@example.com</p>
    <button>Chỉnh sửa</button>
</Card>
💡 Mẹo: children prop rất mạnh mẽ! Dùng nó để tạo layout components (Card, Modal, Sidebar) cho phép custom nội dung bên trong.

5. One-Way Data Flow

Dữ liệu trong React chỉ chảy một chiều: từ cha xuống con. Con muốn thay đổi dữ liệu cha? Cha truyền callback function qua props.

function Parent() {
    const [message, setMessage] = useState('Hello');

    // Truyền callback function cho con
    const handleChange = (newMsg) => {
        setMessage(newMsg);
    };

    return (
        <div>
            <p>Message: {message}</p>
            <Child onMessageChange={handleChange} />
        </div>
    );
}

function Child({ onMessageChange }) {
    return (
        <button onClick={() => onMessageChange('Updated!')}>
            Thay đổi message cha
        </button>
    );
}

📝 Tóm Tắt