Q1. What is conditional rendering in React?
Conditional rendering is a technique to render different UI elements based on a condition.
It works like JavaScript conditionals: you can use if statements, ternary operators, or logical && to decide what to render.
This allows dynamic interfaces.
It works like JavaScript conditionals: you can use if statements, ternary operators, or logical && to decide what to render.
This allows dynamic interfaces.
Q2. How do you use if statements for conditional rendering?
You can use if-else outside the JSX.
For example,
Inside JSX, you can't use if, but you can use ternary or &&.
For example,
if (isLoggedIn) { return <UserGreeting />; } else { return <GuestGreeting />; }.Inside JSX, you can't use if, but you can use ternary or &&.
Q3. What is the ternary operator for conditional rendering?
The ternary operator is used inside JSX:
It's concise and good for simple conditions.
Example:
{condition ? <ComponentA /> : <ComponentB />}.It's concise and good for simple conditions.
Example:
{isLoggedIn ? <LogoutButton /> : <LoginButton />}Q4. How does the logical && operator work for conditional rendering?
The && operator renders the right-hand side if the left-hand side is true.
Example:
If the left side is false, nothing renders.
Example:
{unreadMessages.length > 0 && <p>You have {unreadMessages.length} messages.</p>}.If the left side is false, nothing renders.
Q5. What is the best practice for conditional rendering?
Use ternary for simple if-else, && for single condition, and if-else outside JSX for complex logic.
Also consider using element variables to store conditional elements for readability.
Also consider using element variables to store conditional elements for readability.
