Trong React, conditional rendering được thực hiện bằng các biểu thức JavaScript thông thường. Các cách phổ biến:
1. Toán tử ba ngôi (Ternary operator): Dùng để toggle giữa 2 thành phần.
{isLoggedIn ? <Dashboard /> : <Login />}2. Toán tử Logical AND (&&): Dùng để hiển thị hoặc ẩn một thành phần.
{isLoading && <Spinner />}(Cảnh báo: Tránh dùng count && <List />. Nếu count là 0, React sẽ render số 0. Hãy dùng count > 0 && <List />)
3. Lệnh if/else (hoặc switch): Dùng bên ngoài câu lệnh return cho các logic phức tạp, thường gán kết quả vào một biến rồi render.
In React, conditional rendering is handled using standard JavaScript expressions. Common approaches include:
1. Ternary operator: Used to toggle between two components.
{isLoggedIn ? <Dashboard /> : <Login />}2. Logical AND (&&) operator: Used to conditionally show or hide a component.
{isLoading && <Spinner />}(Warning: Avoid count && <List />. If count is 0, React will render the number 0. Use count > 0 && <List /> instead)
3. if/else (or switch) statements: Used outside the return statement for complex logic, often assigning the result to a variable that is then rendered.