-
Notifications
You must be signed in to change notification settings - Fork 0
/
useShadowRoot.ts
32 lines (31 loc) · 1.12 KB
/
useShadowRoot.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { useLayoutEffect, useRef, useState } from "react";
import type { RefObject } from "react";
/**
* Creates a `shadow DOM tree` for the container, returns it's `shadow root`.
*
* If the shadow DOM tree is already there, returns it's shadow root.
*
* @param {RefObject<Element>} ref The container to attach the shadow DOM tree. Please note that not all elements can have a shadow DOM tree.
* @param {ShadowRootInit} init The initial options of the shadow root.
*/
export function useShadowRoot(shadowHostRef: RefObject<Element>, init: ShadowRootInit)
{
const hasAttachedRef = useRef(false);
const [shadowRoot, setShadowRoot] = useState<ShadowRoot>();
useLayoutEffect(() =>
{
if (!hasAttachedRef.current && shadowHostRef.current)
{
hasAttachedRef.current = true;
if (shadowHostRef.current.shadowRoot)
{
setShadowRoot(shadowHostRef.current.shadowRoot);
}
else
{
setShadowRoot(shadowHostRef.current.attachShadow(init));
}
}
}, [init, shadowHostRef]);
return shadowRoot;
}