Skip to main content

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 provide lwc:if and lwc:else directives for conditional rendering. These directives are evaluated at render time and determine which template blocks to display.

Implementation

import { LightningElement } from 'lwc';

export default class HelloConditionalRendering extends LightningElement {
    areDetailsVisible = false;

    handleChange(event) {
        this.areDetailsVisible = event.target.checked;
    }
}

Key Concepts

The lwc:if Directive

The lwc:if directive conditionally renders a template block:
<template lwc:if={areDetailsVisible}>
    These are the details!
</template>
  • 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

The lwc:else directive provides an alternative when the condition is false:
<template lwc:else>
    Not showing details.
</template>
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:
areDetailsVisible = false;
Checkbox inputs work perfectly with boolean properties because event.target.checked returns true or false:
handleChange(event) {
    this.areDetailsVisible = event.target.checked;
}

What You’ll See

  1. Initial state: Checkbox is unchecked, displays “Not showing details.”
  2. Checked: Check the box to see “These are the details!”
  3. Unchecked: Uncheck to return to “Not showing details.”

Additional Conditional Directives

lwc:elseif

For multiple conditions, use lwc:elseif:
<template lwc:if={status === 'success'}>
    Success!
</template>
<template lwc:elseif={status === 'error'}>
    Error occurred.
</template>
<template lwc:else>
    Processing...
</template>
Use lwc:elseif for mutually exclusive conditions to keep your template clean and efficient.

Best Practices

Remove from DOM: lwc:if completely removes elements from the DOM when false, improving performance compared to CSS display: none.
Boolean coercion: The conditional expression is coerced to a boolean. Empty strings, null, undefined, 0, and false are all falsy.
Complex conditions: For complex boolean logic, use a getter instead of inline expressions:
get shouldShowDetails() {
    return this.isAdmin && this.hasPermission && this.dataLoaded;
}
<template lwc:if={shouldShowDetails}>
    <!-- content -->
</template>

Next Steps

Build docs developers (and LLMs) love