Skip to content

Instantly share code, notes, and snippets.

@JLarky
Last active July 10, 2023 09:23
Show Gist options
  • Save JLarky/80c6b9638db1b13b40e505bd41ba4693 to your computer and use it in GitHub Desktop.
Save JLarky/80c6b9638db1b13b40e505bd41ba4693 to your computer and use it in GitHub Desktop.
How to use shadow dom to isolate CSS of React component https://twitter.com/JLarky/status/1657989891526123520
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>;
}
export function IsolateCSS(props: { children: React.ReactNode }) {
const containerRef = useRef<HTMLDivElement>(null);
const onceRef = useRef(false);
const [shadowRoot, setShadowRoot] = useState<ShadowRoot>();
useEffect(() => {
const container = containerRef.current;
if (container && onceRef.current === false) {
onceRef.current = true;
setShadowRoot(container.attachShadow({ mode: 'open' }));
}
}, []);
return (
<div ref={containerRef}>{shadowRoot && createPortal(props.children, shadowRoot)}</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment