Last active
July 10, 2023 09:23
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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