Trong dấu ngoặc nhọn {} của JSX, bạn chỉ có thể đặt biểu thức (expressions) — tức là đoạn code có thể trả về một giá trị.
Bạn không thể dùng câu lệnh (statements) như if, for, while bên trong JSX. Nguyên nhân là do JSX sẽ được transpile thành một lời gọi hàm trả về object, bạn không thể nhúng câu lệnh if vào giữa các đối số của một hàm.
Cách xử lý trong JSX:
- Thay vì if/else: Dùng toán tử ba ngôi (? :) hoặc logical AND (&&).
- Thay vì vòng lặp for: Dùng hàm Array.prototype.map().
Ví dụ hợp lệ (Expression):
{items.map(i => <li key={i.id}>{i.name}</li>)}Ví dụ KHÔNG hợp lệ (Statement):
{ for (let i of items) { ... } } // ❌ Báo lỗi cú pháp(Mẹo: Nếu logic quá phức tạp, hãy tính toán lưu vào một biến phía trên lệnh return, sau đó nhúng biến đó vào JSX).
Inside JSX curly braces {}, you can only use expressions — pieces of code that evaluate to a value.
You cannot use statements like if, for, or while inside JSX. This is because JSX transpiles into a function call returning an object, and you cannot place an if statement in the middle of function arguments.
How to handle logic in JSX:
- Instead of if/else: Use the ternary operator (? :) or logical AND (&&).
- Instead of for loops: Use Array.prototype.map().
Valid Example (Expression):
{items.map(i => <li key={i.id}>{i.name}</li>)}INVALID Example (Statement):
{ for (let i of items) { ... } } // ❌ Syntax Error(Tip: If the logic is too complex, compute it and store it in a variable above the return statement, then interpolate the variable inside your JSX).