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