Skip to content

Instantly share code, notes, and snippets.

@raynirola
Last active May 17, 2023 04:33
Show Gist options
  • Save raynirola/9a3cae6c640b3aa794be1ec61cc38f11 to your computer and use it in GitHub Desktop.
Save raynirola/9a3cae6c640b3aa794be1ec61cc38f11 to your computer and use it in GitHub Desktop.
export function IsolateCSS(props: { children: React.ReactNode }) {
const onceRef = useRef(false);
const [shadowRoot, setShadowRoot] = useState<ShadowRoot>();
const ref = useCallback((ref: HTMLDivElement | null) => {
if (ref && onceRef.current === false) {
onceRef.current = true;
setShadowRoot(ref.attachShadow({ mode: 'open' }));
}
}, []);
return <div ref={ref}>{shadowRoot && createPortal(props.children, shadowRoot)}</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment