React Fragment (cú pháp <React.Fragment> hoặc viết tắt <>) cho phép nhóm nhiều phần tử con lại với nhau mà không tạo thêm một thẻ DOM thừa (như <div>) bọc bên ngoài.
Khi nào nên sử dụng:
- Khi một component cần return nhiều phần tử cùng cấp.
- Khi nhóm các phần tử bên trong <dl>, <ul>, hoặc <table> (ví dụ: <tr> hoặc <li>) mà thẻ bọc ngoài sẽ làm sai cấu trúc HTML hợp lệ.
Lưu ý về cú pháp:
Cú pháp rút gọn <>...</> không hỗ trợ thuộc tính key. Nếu bạn đang lặp qua một mảng để tạo danh sách Fragment, bạn bắt buộc phải dùng cú pháp đầy đủ: <React.Fragment key={item.id}>...</React.Fragment>.
React Fragment (<React.Fragment> or shorthand <>) lets you group a list of children without adding an extra DOM node (like a <div>) to the actual DOM.
When to use it:
- When a component needs to return multiple sibling elements.
- When grouping elements inside a <dl>, <ul>, or <table> (e.g., <tr> or <li>) where an extra wrapper would result in invalid HTML markup.
Syntax Note:
The shorthand <>...</> does not support the key attribute. If you are mapping over an array to create a list of Fragments, you must use the explicit syntax: <React.Fragment key={item.id}>...</React.Fragment>.