Sub topic 10
Pitfalls and best practices
This chapter assumes you have read the earlier chapters of this tutorial. You should know how default slots, named slots, fallback content, slotchange, and ownership of slotted content work. It collects the mistakes that come up most often when you compose components with slots, explains the mechanism behind each, and ends with a set of working rules.
Why slot bugs are confusing
Most slot problems come from one fact: the parent owns the slotted markup, and the child only decides where it appears. The browser renders slotted content inside the child's layout. In every other respect (styles, data bindings, event handlers, the DOM tree that queries search) the content still belongs to the parent.
When something goes wrong, ask two questions:
- Did the content reach the slot?
- Am I using the owner's tools (the parent's CSS, handlers, and properties) to work with it?
The diagram below turns these questions into a checklist.
Placement and naming mistakes
The slot attribute must be on a direct child
A named slot only receives elements that are direct children of the child component's tag in the parent template. Wrapping the element in another element sends the wrapper to the default slot, and the named slot stays empty.
<!-- parent.html: the header slot stays empty -->
<template>
<c-card>
<div>
<span slot="header">Order summary</span>
</div>
</c-card>
</template>The div is the direct child here, and it has no slot attribute, so it lands in the default slot. The slot="header" on the inner span has no effect. Move the attribute to the direct child:
<!-- parent.html: correct -->
<template>
<c-card>
<div slot="header">
<span>Order summary</span>
</div>
</c-card>
</template>Put the slot attribute on a real element such as div, span, or a base component. Do not rely on it working on a template tag.
Names are static and must match exactly
Slot names are plain strings written into the markup. Treat them as a contract between the two templates:
- Names are case-sensitive.
slot="Header"does not fill<slot name="header">. - A typo does not raise an error. The content is silently not rendered.
- You cannot compute a slot name with an expression such as
slot={position}. If the destination depends on state, render different static markup withlwc:ifblocks in the parent. - Give each slot name one place in the child template. Two slots with the same name are a design smell, because the browser assigns the content to only the first one.
Unslotted content disappears
If the child has no default slot, any parent content without a slot attribute is not shown. If the child has only named slots, the same rule applies. When content "does not show up", check first that the child has a slot that can receive it.
Ownership mistakes
Querying slotted content from the child's template
Slotted elements are not part of the child's template. They are children of the host element. this.template.querySelector() therefore does not find them. Use this.querySelector() instead.
// card.js
import { LightningElement } from 'lwc';
export default class Card extends LightningElement {
renderedCallback() {
// Finds elements the parent placed in any slot
const slotted = this.querySelectorAll('lightning-input');
// Finds only elements in card.html itself
const own = this.template.querySelectorAll('.body');
console.log(slotted.length, own.length);
}
}The two calls are not interchangeable. Pick the one that matches who owns the element. A common bug is a child that calls this.template.querySelector('lightning-input') expecting to validate a form the parent supplied. The call returns null, and the code fails later with a confusing error.
Reaching into the parent's markup is fragile
this.querySelector() works, but it ties the child to whatever markup the parent happens to supply. If the parent switches from lightning-input to a custom input, the child's query returns nothing. Use it for light touches, such as focusing the first input or counting items. For anything with real behavior, use one of these instead:
- A public method on the slotted component, called by the parent.
- An event that the slotted content dispatches and the child listens for.
- A public property that the parent sets.
Styling slotted content from the child
The child's CSS file is scoped to the child's own template. It does not reach elements the parent owns. A rule such as .body p { color: red; } in card.css does not affect the paragraph the parent passes in. Style slotted content in the parent's CSS file, where the elements are defined.
The child still controls everything around the slot: its container, spacing, borders, and layout. Put those styles on the wrapper elements in the child template. Do not count on special selectors that target slotted content from inside the child. Their support differs between the shadow DOM modes that LWC can run in. If the appearance of slotted content must be configurable by the child, expose it through CSS custom properties or SLDS styling hooks that the parent's content inherits.
Binding to the wrong component's data
An expression inside slotted markup is evaluated in the parent. It cannot see the child's fields. This is a common mistake with a card that is supposed to "provide" a title to its content:
<!-- parent.html -->
<template>
<c-card>
<!-- {title} is the PARENT's title, not the card's -->
<p>{title}</p>
</c-card>
</template>LWC slots do not offer scoped slots, so a child cannot pass values back into slotted markup. If the content needs data from the child, either have the parent already hold that data, or make the child render that part itself and expose a property or slot only for the pieces the parent should control.
Event handlers run in the parent
A handler written on slotted markup belongs to the parent:
<!-- parent.html -->
<c-card>
<lightning-button slot="footer" label="Checkout" onclick={handleCheckout}></lightning-button>
</c-card>handleCheckout is a method on the parent class. The card does not run it. If the card must also react to the click, for example to close itself, it can listen on the slot or on a wrapper element, because the event bubbles through the child's template:
<!-- card.html -->
<footer>
<slot name="footer" onclick={handleFooterClick}></slot>
</footer>Remember that listeners in the child see events as they bubble up. They should not assume the exact target type, and they should not call stopPropagation() casually. Stopping the event can break handlers the parent registered on ancestors.
Reacting to content: slotchange gotchas
The slotchange event fires on the slot element when its assigned nodes change. These points cause the most trouble.
- It reports changes to the direct assigned nodes only. It does not fire when something changes inside an assigned element, such as a new child added to a slotted
div. - Do not assume that it fires or does not fire on the first render. Write handlers that compute the correct state from the current assigned nodes and are safe to run repeatedly.
assignedNodes()can include text nodes. A node containing only whitespace should not count as content.- A slot with fallback content reports no assigned nodes when the parent supplied nothing, even though the fallback is visible. Use
assignedNodes()to detect parent content, not the visual state.
A handler that avoids the whitespace trap:
// card.js
import { LightningElement } from 'lwc';
export default class Card extends LightningElement {
hasFooter = false;
handleFooterChange(event) {
const nodes = event.target.assignedNodes();
this.hasFooter = nodes.some(
(node) =>
node.nodeType === Node.ELEMENT_NODE ||
(node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== '')
);
}
get footerClass() {
return this.hasFooter ? 'footer' : 'footer slds-hide';
}
}Start with hasFooter = false, so an empty footer never flashes on screen. The footer appears only after the handler confirms there is content. Use slds-hide only to hide an empty container. Do not use it to hide the slot itself, because slotted content in a hidden container is still created and still running its lifecycle hooks.
Avoid writing state back from the handler in a way that causes a loop. Setting a field that changes the template can re-render the slot. If the re-render reassigns nodes, slotchange can fire again. The code above is safe because it assigns the same boolean value again.
Passing slots through nested components
When a wrapper component forwards its own slot into an inner component, it puts a slot element inside the inner component's tag and gives that element a slot attribute:
<!-- order-panel.html -->
<template>
<c-card>
<slot name="title" slot="header"></slot>
<slot></slot>
</c-card>
</template>This forwards the title slot of c-order-panel to the header slot of c-card, and the default slot to the card's default slot. The forwarding has two consequences:
- From the inner card's point of view, its slot always has an assigned node, namely the forwarding
slotelement. Its fallback content never shows, even when the outermost parent supplied nothing. Put fallback text on the outerslotelement inorder-panel.html, and decide where fallbacks live before you write the layers. - The inner card's
slotchangehandler andassignedNodes()see the forwarding slot, not the final content. CallassignedNodes({ flatten: true })to resolve forwarded slots down to the real nodes.
// card.js: works for direct and forwarded content
handleFooterChange(event) {
const nodes = event.target.assignedNodes({ flatten: true });
this.hasFooter = nodes.length > 0;
}Each extra layer adds more indirection. If you find yourself forwarding more than two levels, consider whether the middle component should expose properties and build the inner markup itself.
Summary of common pitfalls
| Symptom | Likely cause | Fix |
|---|---|---|
| Named slot stays empty | `slot` attribute is not on a direct child, or the name has a typo | Move the attribute to the direct child and match the name exactly |
| Parent content is missing | The child has no slot that can receive it | Add a default slot or the right named slot |
| `this.template.querySelector` returns `null` | Slotted elements are owned by the parent | Use `this.querySelector` |
| Child CSS has no effect on slotted content | Child styles are scoped to the child template | Style it in the parent, or expose custom properties |
| Slotted markup shows the wrong value | Expressions evaluate in the parent | Pass the data from the parent, or render that part in the child |
| Handler never runs the child's logic | Handlers on slotted markup belong to the parent | Handle it in the parent, or listen for the bubbling event on the slot |
| Footer container never hides | Whitespace text node counted as content | Filter whitespace text nodes in the handler |
| Fallback never appears with nested slots | The forwarding `slot` element counts as assigned content | Put fallback on the outermost slot and use `flatten: true` |
Best practices
- Use slots for markup and layout, and use public properties for simple values such as strings, numbers, booleans, and record IDs. A label that is always text should be an
@apiproperty. - Name slots for their role (
header,footer,actions), not for their position or appearance. A name likeleftbecomes wrong when the layout changes. - Always decide what an empty slot should look like. Provide fallback content, or hide the container with
slotchange, or document that the slot is required. - Keep the contract small. Prefer one default slot and a few named slots over many slots that each control a tiny piece of the layout.
- Document the slots at the top of the child's HTML file in a comment. List each name, what belongs there, and whether it is required. Slot names are not discoverable from the parent's side.
- Make the child tolerant of what it receives. Do not assume the slotted element is a particular tag, and do not require a specific number of nodes.
- Prefer events and public methods over DOM queries for communication between the child and slotted components.
- Keep style responsibilities clear. The child styles the structure around the slot, and the parent styles the content in it.
- Keep accessibility in mind. The child cannot know what element the parent put in a heading slot. If the child wraps a slot in
h2, the parent should not also pass anh2. Document the expected content type. - Test the empty case and the changing case. Render the child with no slotted content and with content added and removed at runtime, since those are the two situations that expose logic errors.
Exercises
Exercise
A child component c-panel has <slot name="actions"></slot>. The parent contains <c-panel><div class="toolbar"><lightning-button slot="actions" label="Save"></lightning-button></div></c-panel>. The button never appears. Why, and how do you fix it?
Show answer
The button has the slot attribute, but it is not a direct child of c-panel. Its parent is the div, which has no slot attribute and goes to the default slot (or is dropped if there is none). Move slot="actions" onto the div, or move the button directly under c-panel.
Exercise
A child's renderedCallback calls this.template.querySelector('lightning-input') to validate an input the parent passed in a slot. It returns null. What should the code call, and why?
Show answer
Call this.querySelector('lightning-input'). Slotted elements are owned by the parent and are children of the host element, not part of the child's own template, so this.template does not search them.
Exercise
A wrapper component forwards its default slot to an inner card with <c-card><slot></slot></c-card>. The card has fallback text in its default slot, but the fallback never shows when the outer parent passes nothing. Explain the cause and name two ways to deal with it.
Show answer
The forwarding slot element is itself a node assigned to the card's slot, so the card sees content and hides its fallback. Put the fallback text inside the wrapper's own <slot> element, and have the card use assignedNodes({ flatten: true }) when it needs to know whether real content exists.