Working with Slots and Dynamic Content
Introduction
Nova components are built with Stencil.js and wrapped for React. Because Nova uses the light DOM rather than native shadow DOM, Stencil polyfills slot behavior by physically moving slotted elements into the correct positions within the component's rendered markup. React has no awareness that this DOM manipulation has occurred, which can lead to unexpected behavior when slot content changes dynamically.
This guide shows you how to work with dynamic slot content correctly.
How Slots Work in the Light DOM
When you render children inside a Nova component's slot, Stencil relocates those DOM nodes to match where the <slot> appears in the component's template. From React's perspective, those elements still exist where it originally placed them — but in the actual DOM, they've been moved.
This mismatch is harmless when the slot content is static. This requires extra attention when slot content changes dynamically — for example, when you filter a list, add or remove items, or reorder children. React tries to reconcile its virtual DOM against the real DOM, but the real DOM no longer matches what React expects. This can result in:
- Items not appearing or disappearing when they should
- Duplicate or stale items rendering
- Console errors or visual glitches
- Event handlers becoming detached
A Concrete Example
Consider a dropdown where the items are filtered based on user input:
// This can produce unexpected results
function BrokenExample() {
const [filter, setFilter] = useState('');
const [items] = useState([
{ label: 'Berlin', value: 'berlin' },
{ label: 'Hamburg', value: 'hamburg' },
{ label: 'Munich', value: 'munich' },
]);
const filteredItems = items.filter((item) =>
item.label.toLowerCase().includes(filter.toLowerCase())
);
return (
<NvFielddropdown
filterable
controlledFilter
onFilterTextChanged={(e) => setFilter(e.detail)}
>
<ul slot="content">
{filteredItems.map((item) => (
<NvFielddropdownitem
key={item.value}
label={item.label}
value={item.value}
/>
))}
</ul>
</NvFielddropdown>
);
}
In this example, when the user types a filter and the list of <NvFielddropdownitem> elements changes, React will try to patch the DOM — but Stencil has already moved those nodes. The result is unpredictable rendering.
Keeping Slot Content in Sync
The approach is straightforward: give the parent web component a key that changes whenever its slot content changes. When the key changes, React unmounts the old component instance and mounts a fresh one, which allows Stencil to correctly slot the new children from scratch.
// This works correctly
function WorkingExample() {
const [filter, setFilter] = useState('');
const [items] = useState([
{ label: 'Berlin', value: 'berlin' },
{ label: 'Hamburg', value: 'hamburg' },
{ label: 'Munich', value: 'munich' },
]);
const filteredItems = items.filter((item) =>
item.label.toLowerCase().includes(filter.toLowerCase())
);
return (
<NvFielddropdown
key={filteredItems.map((i) => i.value).join(',')}
filterable
controlledFilter
onFilterTextChanged={(e) => setFilter(e.detail)}
>
<ul slot="content">
{filteredItems.map((item) => (
<NvFielddropdownitem
key={item.value}
label={item.label}
value={item.value}
/>
))}
</ul>
</NvFielddropdown>
);
}
The critical addition is the key on <NvFielddropdown>:
key={filteredItems.map((i) => i.value).join(',')}
Every time the filtered list changes, the key changes, React tears down the old component and creates a new one, and Stencil slots everything correctly.
Key Generation Strategies
The key you choose should change whenever the slot content changes. Here are common approaches:
Joining item identifiers
Best when items have stable, unique IDs:
key={items.map((i) => i.value).join(',')}
Using the array length
Sufficient when items are only added or removed (not reordered):
key={items.length}
Using a counter
Useful when you want explicit control over when to re-mount:
const [revision, setRevision] = useState(0);
// Call this whenever slot content changes
const handleItemsChanged = (newItems) => {
setItems(newItems);
setRevision((r) => r + 1);
};
<NvFielddropdown key={revision}>
{/* ... */}
</NvFielddropdown>
Hashing or serializing
For complex cases where the content shape matters:
key={JSON.stringify(items)}
Tip: Prefer the simplest key that captures meaningful changes. Overly granular keys (like
JSON.stringify) cause more re-mounts than necessary, while overly coarse keys (likeitems.length) may miss reorder changes.
Full Example: Filtered Dropdown
This is a complete working pattern using NvFielddropdown with dynamic filtering. See the Advanced NvFielddropdown Examples for interactive demonstrations.
import { useState, useRef, useMemo } from 'react';
import { NvFielddropdown, NvFielddropdownitem } from '@nova-design-system/nova-react';
function FilteredDropdown() {
const [filter, setFilter] = useState('');
const [value, setValue] = useState('');
const ref = useRef<HTMLNvFielddropdownElement>(null);
const [items, setItems] = useState([
{ label: 'Berlin', value: 'berlin' },
{ label: 'Hamburg', value: 'hamburg' },
{ label: 'Munich', value: 'munich' },
{ label: 'Frankfurt', value: 'frankfurt' },
{ label: 'Cologne', value: 'cologne' },
]);
const filteredItems = useMemo(() => {
if (!filter.trim()) return items;
const lower = filter.toLowerCase();
return items.filter((item) => item.label.toLowerCase().includes(lower));
}, [items, filter]);
// Key changes whenever the filtered results change
const dropdownKey = filteredItems.map((i) => i.value).join(',');
return (
<NvFielddropdown
key={dropdownKey}
ref={ref}
filterable
controlledFilter
value={value}
label="Select a City"
onFilterTextChanged={(e) => setFilter(e.detail)}
onValueChanged={(e) => setValue(e.detail)}
options={filteredItems}
>
<ul slot="content">
{!filteredItems.length && (
<NvFielddropdownitem disabled data-empty>
No results found
</NvFielddropdownitem>
)}
</ul>
</NvFielddropdown>
);
}
When Is This Necessary?
You only need this pattern when slot content changes dynamically. Specifically:
| Scenario | Key needed? |
|---|---|
| Static list of items | No |
| Filtering / searching items | Yes |
| Adding or removing items | Yes |
| Reordering items | Yes |
| Changing props on existing items only | No |
| Toggling visibility of a slot child | Yes |
If your component's slotted children never change after the initial render, no special handling is required.
Caveats
- Component state resets on re-mount. Because changing the
keyunmounts and remounts the component, any internal state (e.g., open/closed state, scroll position, filter text) will be lost. Lift any state you need to preserve into React state above the keyed component. - Refs are reassigned. If you hold a
refto the component, it will point to the new instance after re-mount. This is generally fine, but be aware of it if you're caching the ref value. - Performance. Re-mounting is more expensive than patching. For most use cases this is negligible, but avoid key patterns that change on every render if slot content hasn't actually changed.
Summary
Because Stencil's light-DOM slot polyfill moves DOM nodes in ways that React cannot track, the recommended approach for dynamic slot content is:
When slot content changes dynamically, set a
keyon the parent web component that reflects the current content. This forces React to re-mount the component, keeping React and the web component in sync.