How does conditional rendering work in LWC templates using modern directives?
Answer
Basics: Conditional rendering decides which parts of the template appear. For example, show a spinner while loading, an error panel if a call failed, and content otherwise. The condition must be a simple property or getter, because templates do not allow expressions.
How it works:
<template lwc:if={isLoading}>...</template>renders when the value is truthy.- Immediately following sibling:
<template lwc:elseif={hasError}>...</template>. - Final fallback:
<template lwc:else>...</template>. - The branches must be adjacent siblings; no other element can sit between them.
- Complex logic goes into a getter in JS, such as
get showEmpty() { return !this.isLoading && !this.rows.length; }.
Advanced / deep dive: lwc:if (Spring '23 and later) is the supported directive; if:true and if:false still work but are legacy and cannot express else-if chains, so migrate when touching the code. Do not mix legacy and new directives on the same chain. When a branch is false, its DOM and child components are destroyed; when it becomes true they are created again, firing child connectedCallback and losing child state and unsaved input. If you need to preserve state or avoid recreation cost, hide with a CSS class like slds-hide instead. Removing large subtrees repeatedly is costly, so for frequently toggled sections consider hiding. Also remember conditionals interact with renderedCallback: elements in a false branch will be null when you query them. Evaluate order matters: the first truthy branch wins.
Code / config example:
< =>
{errorMessage}