Sub topic 2
Why Render Conditionally?
Prerequisites
This chapter assumes you can read a Lightning Web Component (LWC) as an HTML template plus a JavaScript class. It also assumes you can bind a class field in a template with curly braces, such as {owner}, and that you know a reactive field re-renders the template when its value changes. You should be comfortable with ES module syntax, classes, and getters. The next chapters cover the syntax in detail. This one explains why the technique exists and what it does to the DOM.
The problem: one component, many states
A component rarely has one appearance. A record card is empty before data arrives and shows a spinner while a request runs. It shows an error if the request fails, and the record itself when it succeeds. A form shows an "Edit" button to users who can edit and nothing to those who can't. A panel is collapsed until the user expands it.
A template is static markup with bindings. It describes every element the component could ever show. Without a way to choose, you would have two options:
- Render everything all the time, which shows a spinner and an error message next to real data.
- Build the DOM by hand in JavaScript with
document.createElement, which gives up the declarative template.
Conditional rendering solves this. You mark parts of the template as present only when a condition about the component's state is true. The template stays declarative, and the framework works out which DOM nodes to add or remove.
What conditional rendering means
Conditional rendering is a template mechanism that decides whether a block of markup exists in the DOM, based on a value from the component. The key word is exists. When the condition is false, the block is not hidden. It is not in the DOM tree at all. The elements are not created, and a child component inside the block is not instantiated.
This differs from CSS hiding, where an element stays in the DOM and a style such as display: none stops it from painting. The last chapters of this tutorial compare the two. For now, remember the basic rule: conditional rendering changes the DOM, and CSS hiding changes only its appearance.
A first look at the syntax
In current LWC, the directive for this is lwc:if. You put it on a <template> tag (or on an element) and bind it to a property or getter. The block renders only when the bound value is truthy. Chapter 4 covers the directive in detail. Here is a small example so the rest of this chapter has something concrete to refer to.
<template>
<lightning-button
label={buttonLabel}
onclick={handleToggle}
></lightning-button>
<template lwc:if={showDetails}>
<p class="details">Account owner: {owner}</p>
</template>
</template>import { LightningElement } from 'lwc';
export default class AccountSummary extends LightningElement {
showDetails = false;
owner = 'Dana Lee';
get buttonLabel() {
return this.showDetails ? 'Hide details' : 'Show details';
}
handleToggle() {
this.showDetails = !this.showDetails;
}
}On first render, showDetails is false, so the browser's DOM contains the button and no <p>. Clicking the button flips the field. The framework notices the change, re-evaluates the condition, and inserts the paragraph. Clicking again removes it.
The data flow behind a toggle
The component's state drives everything. You never tell the framework to "show this paragraph". You change a field, and the template follows.
This is the model to keep in mind. The event handler's job is to update state. The template's job is to describe what the UI looks like for that state. Because the two are separate, you can reason about the UI by looking at the state alone.
Where conditions come from
A condition is any property on the component that the template can read. In practice there are three sources:
- A plain field you set yourself, such as
showDetailsabove. Handlers toggle it in response to clicks. - A field filled by data access, such as the result of a
@wireadapter or an imperative Apex call. For example, adataproperty isundefineduntil the request completes. - A getter that computes a boolean from other state, such as
get isEmpty() { return this.items.length === 0; }.
LWC templates do not allow arbitrary JavaScript expressions in the condition. You cannot write lwc:if={items.length === 0}. The condition must be a simple property reference, so any comparison or combination belongs in a getter. Chapter 6 covers this.
Why this matters beyond appearance
Conditional rendering is more than a cosmetic tool. It has practical effects that you will meet in real components.
Guarding against missing data
Data often arrives after the first render. If your template reads a nested property of something that is still undefined, the read throws a TypeError. With wired data that looks like account.data.Name, the first render happens before data exists. Wrapping the block in a condition on account.data keeps the template from touching a value that isn't there yet.
Controlling cost
A block that is not rendered costs nothing. Its child components are not created, their connectedCallback hooks do not run, and any requests those children would make never happen. A tab panel that contains a heavy child component is a good candidate. Render the panel only when its tab is active, and you skip the work for the tabs the user never opens. Hiding the panel with CSS would still create the child and run its setup.
Enforcing what the user can do
Showing a delete button only when canDelete is true keeps the UI honest, but it is not security. A user can open the browser's developer tools and alter the DOM, and your server logic must still check permissions. Treat conditional rendering as a way to present the interface well and not as an access control.
Resetting state
When a branch is removed, the components inside it are destroyed. When it returns, new instances are created with fresh state. This can be useful, because a form inside a modal starts clean each time it opens. It can also surprise you, because a user's half-typed input in a removed branch is gone. Chapter 13 covers the lifecycle details.
Edge cases to know now
Some behaviors are easy to miss at this stage:
- Queries find nothing for absent content. In the example above,
this.template.querySelector('.details')returnsnullwhileshowDetailsis false. Code inrenderedCallbackthat assumes the element exists will fail. - The condition is evaluated for truthiness, not strict
true. A non-empty string, a non-zero number, or an object passes.0,'',null,undefined, andNaNfail. Chapter 3 covers this. Be careful with a list length: an empty array is truthy, butarray.lengthof0is falsy. - Updates happen on the next render, not instantly. Setting a field in a handler schedules a re-render. Code that runs right after the assignment does not yet see the new DOM.
- State must be reactive. In LWC, class fields are reactive for reassignment. Mutating a nested property of a plain object or array in place may not trigger a re-render for the condition that depends on it. Reassign the field when in doubt.
Choosing when to render conditionally
The following table gives a first rule of thumb. Chapter 14 returns to it with more detail.
| Situation | Better choice | Reason |
|---|---|---|
| Content depends on data that may be missing | Conditional rendering | Avoids reading properties of `undefined` |
| Block holds an expensive child component | Conditional rendering | The child is not created until needed |
| Content toggles many times per second | Consider CSS hiding | Avoids repeated creation and destruction |
| Child must keep its internal state between toggles | CSS hiding | The instance stays alive |
| Choosing between mutually exclusive states | Conditional rendering with a chain | Exactly one branch exists at a time |
Common mistakes at this level
- Putting logic in the template. Template conditions only accept a property reference, so move comparisons into getters.
- Treating
lwc:ifas a visibility switch and then querying for the element while it is absent. - Using conditional rendering as a security check.
- Rendering several independent
lwc:ifblocks for states that are mutually exclusive, which lets two blocks appear together when state is inconsistent. Chains, covered later, prevent this.
Exercise
A component renders a heavy child component inside a block controlled by lwc:if={isOpen}. isOpen starts as false. After the component loads, how many instances of the child exist, and what does this.template.querySelector return for a selector that matches an element inside that block?
Show answer
Zero instances exist, because the block is not in the DOM when the condition is falsy, so the child is never created. The query returns null. Once isOpen becomes truthy, the framework creates the child and the query can find the element after the next render.
Exercise
A wired property account has the shape { data, error }, and data is undefined until the request completes. Explain why a template that renders {account.data.Name} directly fails on first render, and how conditional rendering fixes it.
Show answer
On first render account.data is undefined, so reading Name from it throws a TypeError. Wrapping the paragraph in a block with lwc:if={account.data} means the block is absent until data is truthy, so the template never reads Name from undefined.