Conditional Rendering in React
Displaying UI elements based on conditions.
In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like `if` or the conditional operator (ternary operator) to create elements representing the current state, and let React update the UI to match them.
Common Techniques:
- If/Else Statements: You can use standard JavaScript `if/else` statements to prepare which component or element to render.
let displayElement; if (isLoggedIn) { displayElement = <UserGreeting />; } else { displayElement = <GuestGreeting />; } return <div>{displayElement}</div>; - Ternary Operator: For inline conditional logic, the ternary operator is very common.
return <div>{isLoggedIn ? <UserGreeting /> : <GuestGreeting />}</div>; - Logical && Operator: Useful for rendering an element only if a condition is true.
return <div>{unreadMessages.length > 0 && <h2>You have {unreadMessages.length} unread messages.</h2>}</div>; - Preventing Rendering with `null`: You can have a component render nothing by returning `null`.
Live Example:
Please log in.
Test Your Knowledge
Question 1/3
What is conditional rendering in React?