React Conditional Rendering

Conditional rendering controls which parts of the UI are displayed based on specific conditions. It is widely used to show or hide elements depending on user input, data state, or system status. This helps keep the interface relevant and responsive to changes. Displays different UI elements based on the current state or props. Automatically updates what the user sees when data or conditions change. Removes the need to manually manipulate the DOM to show or hide content. Implementation of Conditi
Conditional rendering controls which parts of the UI are displayed based on specific conditions. It is widely used to show or hide elements depending on user input, data state, or system status. This helps keep the interface relevant and responsive to changes.
- Displays different UI elements based on the current state or props.
- Automatically updates what the user sees when data or conditions change.
- Removes the need to manually manipulate the DOM to show or hide content.
Implementation of Conditional Rendering
- Using If/Else Statements If/else statements allow rendering different components based on conditions. This approach is useful for complex conditions.
function Item({ name, isPacked }) {
if (isPacked) {
//name="Book"
return <li className="item">{name}✔</li>;
}
return <li className="item">{name}</li>;
}
- If isPacked is true, it displays: Book✔
- If isPacked is false, it displays: Book
2. Using Ternary Operator
The ternary operator (condition ? expr1: expr2) is a concise way to conditionally render JSX elements. It’s often used when the logic is simple, and there are only two options to render.
function Greeting({ isLoggedIn }) {
return <h1>{isLoggedIn ? "Welcome Back!" : "Please Sign In"}</h1>;
}
- If isLoggedIn is true: Welcome Back!
- If isLoggedIn is false: Please Sign In
3. Using Logical AND (&&) Operator
The && operator returns the second operand if the first is true, and nothing if the first is false. This can be useful when you only want to render something when a condition is true.
- If hasNotifications is true: You have new notifications!
- If hasNotifications is false: Nothing is rendered.




