Overview
Conditional rendering allows you to show or hide portions of your template based on component state. This is essential for creating dynamic user interfaces that respond to user actions and data conditions.How It Works
Lightning Web Components providelwc:if and lwc:else directives for conditional rendering. These directives are evaluated at render time and determine which template blocks to display.
Implementation
Key Concepts
The lwc:if Directive
Thelwc:if directive conditionally renders a template block:
- The expression in curly braces
{areDetailsVisible}is evaluated as a boolean - If truthy, the template block is rendered
- If falsy, the block is removed from the DOM
The lwc:else Directive
Thelwc:else directive provides an alternative when the condition is false:
The
lwc:else block must immediately follow an lwc:if block. You cannot have other elements between them.Boolean Properties
In this example,areDetailsVisible is a boolean property:
event.target.checked returns true or false:
What You’ll See
- Initial state: Checkbox is unchecked, displays “Not showing details.”
- Checked: Check the box to see “These are the details!”
- Unchecked: Uncheck to return to “Not showing details.”
Additional Conditional Directives
lwc:elseif
For multiple conditions, uselwc:elseif:
Best Practices
Boolean coercion: The conditional expression is coerced to a boolean. Empty strings,
null, undefined, 0, and false are all falsy.Next Steps
- Expressions - Compute values using getters
- Iteration - Render lists with for:each and iterator
- Data Binding - Handle user input
