Trong JSX:
- null, undefined, true, và false: React sẽ bỏ qua hoàn toàn và không render ra bất kỳ thứ gì trên DOM. (Điều này cho phép dùng && để conditional rendering).
- Chuỗi rỗng (""): Sẽ render ra một text node rỗng.
Cạm bẫy với số 0 (Falsy values):
Mặc dù số 0 hoặc NaN là falsy trong JavaScript, React vẫn sẽ render chúng thành text.
Ví dụ lỗi:
{count && <List />} // Nếu count = 0, màn hình sẽ in ra số "0"Cách khắc phục:
Đảm bảo biểu thức bên trái toán tử && luôn là một Boolean (true/false) bằng cách dùng phép so sánh hoặc ép kiểu:
{count > 0 && <List />}
// Hoặc:
{!!count && <List />}In JSX:
- null, undefined, true, and false: React completely ignores them and renders nothing to the DOM. (This is what makes the && operator work for conditional rendering).
- Empty string (""): Renders an empty text node.
The pitfall with the number 0 (Falsy values):
Although 0 or NaN are falsy in JavaScript, React will still render them as text strings on the screen.
Bug Example:
{count && <List />} // If count = 0, it renders "0" to the UI.How to fix:
Ensure the expression on the left side of the && operator evaluates to a strict Boolean (true/false) by using a comparison or casting:
{count > 0 && <List />}
// Or:
{!!count && <List />}