🔗
Slot as templates

Introduction

Slots are a powerful feature when working with webcomponents that use the shadowDOM and thanks to the hook @atomico/hooks/use-slot you will be able to observe the state of the slot and know the childNodes of this to manage the logic of the template, example:
1
import { useRef } from "atomico";
2
import { useSlot } from "@atomico/hooks/use-slot";
3
4
function component() {
5
const refSlotIcon = useRef();
6
const slotIcon = useSlot(refSlotIcon);
7
return (
8
<host shadowDom>
9
<slot
10
name="icon"
11
ref={refSlotIcon}
12
style={slotIcon.length ? null : "display: none"}
13
/>
14
<slot />
15
</host>
16
);
17
}
Copied!
Thus managing to easily condition parts of our template to define the slots.
Another trick that useSlot allows us is the interaction at the DOM level, example:
1
import { useRef, useEffect } from "atomico";
2
import { useSlot } from "@atomico/hooks/use-slot";
3
4
function component() {
5
const refSlotSlides = useRef();
6
const slotSlides = useSlot(refSlotSlides);
7
8
slotSlides.forEach((slide) => {
9
slide.style.width = "100%";
10
slide.style.height = "300px";
11
});
12
13
return (
14
<host shadowDom>
15
<slot name="slides" />
16
</host>
17
);
18
}
Copied!
We can even apply filters per instance for a better identification of the node, example:
1
useSlot(refSlotSlides).filter(
2
(childNode) => childNode instanceof HTMLDivElement
3
);
Copied!
⚠️ In case of high ui computation use prefer to use slot modifiers inside a useEffect.

Slot pattern as a template

Slots are not only limited to a static definition, you can use them to identify a node and use it to create new nodes according to the logic of the webcomponent, example:
1
import { useRef } from "atomico";
2
import { useSlot } from "@atomico/hooks/use-slot";
3
import { usePromise } from "@atomico/hooks/use-promise";
4
5
function userFetch() {
6
const refSlotTemplateUser = useRef();
7
const [Template] = useSlot(refSlotTemplateUser);
8
const [result, status] = usePromise(
9
() =>
10
fetch("https://jsonplaceholder.typicode.com/users").then((res) =>
11
res.json()
12
),
13
true
14
);
15
16
return (
17
<host shadowDom>
18
<slot name="template" ref={refSlotTemplateUser} />
19
<div class="list">
20
{status === "fulfilled"
21
? !!Template &&
22
result.map((props) => <Template {...props} cloneNode />)
23
: "Pending..."}
24
</div>
25
</host>
26
);
27
}
Copied!
Thanks to useSlot(refSlotTemplateUser) we get the first node of the Template slot to be used in the iteration of the results obtained by fetch, with this we have eliminated the leverage of the webcomponent in charge of rendering the user at the level of our webcomponent userFetch

Example

WebComponents.dev
WebComponents.dev
⚠️ the cloneNode property is available from version [email protected]
Copy link
Edit on GitHub