Sub topic 4
Fallback content for empty slots
A slot is a placeholder in a child component's template. A parent can fill it, or leave it empty. This chapter covers what the child renders when the parent leaves a slot empty, which is called fallback content. It also covers the edge cases where "empty" doesn't mean what you expect.
This chapter assumes you can build a basic Lightning web component (template, class, CSS file). It also assumes you can use a child component in a parent template, and that you know the default slot and named slots from the previous chapters.
What fallback content is
Fallback content is whatever you put between the opening and closing <slot> tags in the child's template. The browser renders it only when the parent assigns nothing to that slot. If the parent assigns even one node, the fallback is not rendered at all.
<slot name="header">Untitled</slot>Here "Untitled" is the fallback. A parent that writes <span slot="header">Order summary</span> replaces it. A parent that writes nothing for header gets "Untitled".
Fallback content is not limited to text. It can be any markup the child's template allows: elements, base components, other custom components, and bindings to the child's own properties.
A worked example
This panel component has three slots. Each one has fallback content that makes sense on its own.
<!-- panel.html -->
<template>
<section class="panel">
<h2 class="title">
<slot name="title">Untitled panel</slot>
</h2>
<div class="content">
<slot>
<p class="empty">Nothing to show yet.</p>
</slot>
</div>
<footer class="actions">
<slot name="actions">
<lightning-button
label="Close"
onclick={handleClose}
></lightning-button>
</slot>
</footer>
</section>
</template>// panel.js
import { LightningElement } from 'lwc';
export default class Panel extends LightningElement {
handleClose() {
this.dispatchEvent(new CustomEvent('close'));
}
}/* panel.css */
.empty {
color: #706e6b;
font-style: italic;
}Now three parents use the same component.
<!-- parentNone.html: every slot is left empty -->
<template>
<c-panel></c-panel>
</template>This renders the title "Untitled panel", the italic text "Nothing to show yet.", and a Close button.
<!-- parentSome.html: title and content supplied, actions left empty -->
<template>
<c-panel>
<span slot="title">Open cases</span>
<p>You have 4 open cases.</p>
</c-panel>
</template>This renders the supplied title and paragraph. The actions slot is still empty, so the Close button still appears.
<!-- parentAll.html: every slot supplied -->
<template>
<c-panel>
<span slot="title">Open cases</span>
<p>You have 4 open cases.</p>
<lightning-button slot="actions" label="Reassign"></lightning-button>
</c-panel>
</template>This renders only the Reassign button in the footer. The Close button is gone, because the supplied button replaced the entire fallback.
When the fallback renders
The rule is a single check per slot: does the parent assign at least one node to it?
The check is per slot, not per component. In parentSome.html the title and content slots are filled while the actions slot falls back. Each slot decides on its own.
| Parent markup | Target slot | What renders |
|---|---|---|
| Nothing for that slot | Any | Fallback |
| `<span slot="title">Hi</span>` | `title` | The span. No fallback. |
| `<p>Text</p>` with no `slot` attribute | Default | The paragraph. No fallback. |
| Bare text inside `<c-panel>` | Default | The text. No fallback. |
| `<span slot="title"></span>` (empty element) | `title` | An empty span. No fallback. |
| `<template lwc:if={show}>` that is false | The slot it targets | Fallback |
| An element whose `slot` value matches no slot | None | Not rendered anywhere. Fallbacks are unaffected. |
Cases that surprise people
An empty element still counts
Fallback depends on whether a node is assigned, not on whether that node is visible. This parent suppresses the fallback and shows nothing:
<template>
<c-panel>
<span slot="title"></span>
</c-panel>
</template>The span is an element assigned to title, so "Untitled panel" does not render. The heading is blank. This happens often when a parent writes <span slot="title">{title}</span> and title is undefined or an empty string. The span exists, so the fallback is skipped, and the child shows an empty heading.
There are two ways to fix this. The first is to render the element only when there is something to show:
<template>
<c-panel>
<span slot="title" lwc:if={title}>{title}</span>
</c-panel>
</template>When title is falsy, the span is not rendered. No node is assigned, and the fallback appears. This is the pattern to use when the parent has optional data.
The second is to move the choice into the child. A public property can supply the text, and the child can fall back to a default in JavaScript. The slots-or-properties chapter compares these approaches.
Conditional content from the parent
Conditional directives work as you would expect with slots. Content that is not rendered is not assigned. Putting the directive on the slotted element itself is the safest form, as shown above. You can also wrap several slotted elements in a template that has a directive:
<template>
<c-panel>
<template lwc:if={canEdit}>
<lightning-button slot="actions" label="Edit"></lightning-button>
<lightning-button slot="actions" label="Delete"></lightning-button>
</template>
</c-panel>
</template>When canEdit is false, both buttons are absent and the Close fallback appears. When it is true, both buttons render and Close disappears.
Fallback is all or nothing
Fallback content is not merged with parent content. If the parent supplies one node, the whole fallback is replaced. A parent cannot say "add my button next to your Close button." If the child wants a Close button to always be present, it should place the button outside the slot:
<footer class="actions">
<slot name="actions"></slot>
<lightning-button label="Close" onclick={handleClose}></lightning-button>
</footer>Use fallback for content that is a default. Use markup outside the slot for content that is required.
Whitespace and comments
You may worry that a parent's line breaks and indentation count as content. In an LWC template they do not. The compiler drops whitespace-only text between elements, so this parent leaves the slot empty:
<template>
<c-panel>
</c-panel>
</template>Likewise, HTML comments in templates are removed by default, so a comment inside <c-panel> does not assign a node. Real text does count. A parent that writes <c-panel>-</c-panel> assigns a text node to the default slot, and the fallback disappears.
The same applies inside the child. Whitespace between <slot> and </slot> is not fallback content, so you don't need to worry about spacing in the child's markup.
Fallback is owned by the child
The fallback content is part of the child's template. That ownership decides styling, bindings, and events.
| Concern | Fallback content (child-owned) | Slotted content (parent-owned) |
|---|---|---|
| Styles | The child's CSS file applies | The parent's CSS file applies |
| Data bindings | Expressions read the child's properties and getters | Expressions read the parent's properties and getters |
| Event handlers | Methods on the child's class | Methods on the parent's class |
The example above shows this. The .empty rule in panel.css styles the "Nothing to show yet." paragraph, because that paragraph belongs to the child's template. If the parent had a .empty rule in its own CSS, it would not affect the fallback. And onclick={handleClose} calls the child's method, which dispatches a close event. The parent listens with onclose:
<template>
<c-panel onclose={handlePanelClose}></c-panel>
</template>If the parent instead supplies its own button for the actions slot, its click handler is a method on the parent's class. The child's handleClose never runs, and no close event fires unless the parent dispatches or handles something itself. Keep this in mind when you design a child that depends on its fallback to emit events. Once the parent replaces the fallback, those events stop.
Child-owned fallback can use any binding the child has:
<slot name="title">{defaultTitle}</slot>// in panel.js
get defaultTitle() {
return this.recordName ? `Panel for ${this.recordName}` : 'Untitled panel';
}Here recordName would be an @api property on the child. The fallback updates reactively when that property changes, and it appears only while the slot is empty.
Detecting that the fallback is showing
The slotchange event and assignedNodes() method are covered in later chapters. This section covers only how they relate to fallback.
assignedNodes() on a slot returns the nodes the parent assigned. When the slot is showing its fallback, nothing is assigned, so it returns an empty array. Fallback elements are not in that list. This means the footer example from the spine works with both states:
// card.js
import { LightningElement } from 'lwc';
export default class Card extends LightningElement {
hasFooter = false;
handleFooterChange(event) {
const slot = event.target;
this.hasFooter = slot.assignedNodes().length > 0;
}
get footerClass() {
return this.hasFooter ? 'footer' : 'footer slds-hide';
}
}That code answers the question "did the parent supply anything?" It does not answer "is anything visible in that slot?" If a slot has fallback content, a result of zero assigned nodes means the fallback is showing. Be careful with the choice between a fallback and this hide-the-container pattern:
- If an empty slot should show something useful, give it fallback content.
- If an empty slot should show nothing and should not leave an empty container with padding or borders, leave the slot without fallback and hide the container with
slotchange, ascarddoes for its footer.
In the card component from the spine, the header slot uses fallback ("Untitled"), and the footer slot uses no fallback and the hide pattern. Both choices fit their purposes. A footer with a default "Untitled" would make no sense.
Do not combine the two on the same slot unless you mean to. A slot with fallback content always has something visible when empty, so hiding its container because assignedNodes() is empty would hide the fallback too.
Designing good fallbacks
Choose fallback content deliberately. These guidelines cover most cases:
- Make the empty component usable. A component rendered with no slot content should still look intentional. "Untitled" and "Nothing to show yet." read as a deliberate state.
- Keep it short. Fallback is a placeholder. If you find yourself writing a large block of markup in a slot, consider whether it should be a separate child component.
- Match the role of the slot. A title slot gets text, an actions slot gets a sensible default action, a content slot gets an empty-state message.
- Don't put required behavior in fallback. Anything that must always exist belongs outside the slot, since the parent can replace fallback at any time.
- Make text translatable. Hard-coded strings such as "Untitled" are fine in an example. In a shipped component, use custom labels (
@salesforce/label/...) imported into the child and bind them as{label.untitled}. - Test both states. Write a test that renders the component with the slot empty and another that fills it. Check the fallback text in the first and its absence in the second.
Fallback or `lwc:if`?
A child might be tempted to branch in its own template instead of using fallback:
<template lwc:if={hasTitle}>
<slot name="title"></slot>
</template>
<template lwc:else>
Untitled
</template>This is the wrong tool. The child cannot know from its own data whether the parent supplied a slot. hasTitle would have to be set from slotchange, which fires after the first render and causes an extra rerender and a flicker. Native fallback needs no JavaScript and is correct on the first render. Use lwc:if for decisions based on the child's own state, and use fallback for "the parent gave me nothing."
Common errors
- Blank heading instead of default text. The parent renders an empty element into the slot, so the fallback is suppressed. Put the conditional directive on the slotted element so that no node exists when the value is empty.
- Fallback button vanishes after adding another button. The parent's single node replaced the whole fallback. Move required controls outside the slot.
- Style rule in the parent does not affect the fallback. The fallback belongs to the child. Style it in the child's CSS.
- Click handler does nothing after the parent fills the slot. The handler lived on the fallback in the child. A parent-supplied replacement needs its own handler.
- Content with a mistyped
slotvalue never appears, and the fallback still shows. A name that matches no slot assigns the node nowhere. Check that theslotattribute matches thenameexactly, including case.
Exercises
Exercise
A parent writes <span slot="title">{heading}</span> inside <c-panel>. When heading is an empty string, the panel shows a blank title instead of "Untitled panel". Why does this happen, and how do you change the parent so the fallback appears?
Show answer
The span is an element assigned to the title slot even though it has no text, so the slot has assigned nodes and the fallback is skipped. Put a conditional directive on the span, for example <span slot="title" lwc:if={heading}>{heading}</span>. When heading is empty, no node is rendered, nothing is assigned to the slot, and "Untitled panel" renders.
Exercise
The panel component's actions slot has a fallback Close button wired to handleClose. A parent supplies <lightning-button slot="actions" label="Reassign">. Which of these happen: (a) Close and Reassign both show, (b) only Reassign shows, (c) clicking Reassign runs handleClose? How would you change the child so Close always shows?
Show answer
Only (b) happens. The supplied button replaces the whole fallback, so Close is not rendered, and a click on Reassign runs whatever handler the parent attached, not the child's handleClose. To always show Close, move the button out of the slot: place <slot name="actions"></slot> and then a separate <lightning-button label="Close" onclick={handleClose}> inside the footer.
Exercise
You want a card footer that has no visible container at all when the parent supplies nothing, and a card header that shows "Untitled" when the parent supplies nothing. Which technique does each slot use?
Show answer
The header slot uses fallback content: <slot name="header">Untitled</slot>. The footer slot uses no fallback. It uses an onslotchange handler that sets a flag from assignedNodes().length > 0, and a getter adds slds-hide to the footer container when the flag is false.