Working with Slotted Content
Last updated
<div slot="slot">
<div class="w-dyn-list">...</div>
<div class="w-dyn-list">...</div>
</div>interface Props { content?: React.ReactNode; }
export function Wrapper({ content }: Props) {
const transformed = React.Children.map(content, child => {
if (React.isValidElement(child) && child.type === 'img') {
return React.cloneElement(child, { loading: 'lazy', decoding: 'async' });
}
return child;
});
return <div>{transformed}</div>;
}import { useEffect, useRef } from "react";
export function WithSlot() {
const anchorRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const root = (anchorRef.current?.getRootNode?.() as ShadowRoot | null) ?? null;
const slot = root?.querySelector('slot[name="slot"]') as HTMLSlotElement | null;
const assigned = slot?.assignedElements({ flatten: true }) ?? [];
// example manipulation
for (const el of assigned) el.setAttribute('data-injected', '1');
}, []);
return (
<div ref={anchorRef}>
<slot name="slot" />
</div>
);
}