Conditional Rendering
40 minIn 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.
You can use JavaScript operators like `if` or the conditional operator `condition ? true : false` to create elements representing the current state.
This allows you to show or hide components or elements dynamically.
The logical AND operator (&&) is commonly used for conditional rendering when you want to render something or nothing.
Early returns in components provide a clean way to handle conditional rendering, especially for authentication or loading states.
Ternary operators are ideal for simple if-else scenarios, while if statements work better for complex conditional logic.
Key Concepts
- Conditional rendering uses JavaScript conditionals in JSX.
- Ternary operator (condition ? true : false) handles if-else cases.
- Logical AND (&&) renders content only when condition is true.
- Early returns can simplify complex conditional rendering.
- Null and undefined are valid return values that render nothing.
Learning Objectives
Master
- Using ternary operators for conditional rendering
- Implementing logical AND for conditional display
- Using early returns for complex conditions
- Handling null and undefined in conditional rendering
Develop
- Thinking in terms of conditional UI states
- Choosing the right conditional pattern for each scenario
- Writing readable conditional rendering code
Tips
- Use ternary operators for simple if-else scenarios.
- Use logical AND (&&) when you only need to render on true condition.
- Extract complex conditionals into variables for readability.
- Consider using early returns for authentication or loading states.
Common Pitfalls
- Using && with falsy values like 0 or empty string, which still render.
- Creating deeply nested ternary operators that are hard to read.
- Not handling all possible states in conditional rendering.
- Forgetting that 0 is falsy and will render as '0' in JSX.
Summary
- Conditional rendering uses JavaScript conditionals in JSX.
- Ternary operators handle if-else scenarios elegantly.
- Logical AND is useful for simple conditional display.
- Early returns simplify complex conditional logic.
Exercise
Create a component that renders a 'Login' button if the user is logged out, and a 'Logout' button if they are logged in.
function LoginControl(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <button>Logout</button>;
}
return <button>Login</button>;
}
// Usage: <LoginControl isLoggedIn={false} />
Exercise Tips
- Try using a ternary operator instead of if-else.
- Add loading state handling for async authentication.
- Consider extracting the button into a separate component.
- Add onClick handlers to actually implement login/logout.