shadow-root-portal.tsx 921 B

1234567891011121314151617181920212223242526272829303132
  1. import { FC, PropsWithChildren, useEffect, useRef, useState } from 'react'
  2. import { createPortal } from 'react-dom'
  3. // @ts-expect-error this is using exportType: 'css-style-sheet'
  4. import tailwindCSS from '../tailwind.css'
  5. export const ShadowRootPortal: FC<PropsWithChildren> = ({ children }) => {
  6. const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(null)
  7. const hostRef = useRef<HTMLDivElement | null>(null)
  8. useEffect(() => {
  9. if (!shadowRoot && hostRef.current) {
  10. const shadowRoot = hostRef.current.attachShadow({ mode: 'open' })
  11. shadowRoot.adoptedStyleSheets = [tailwindCSS]
  12. setShadowRoot(shadowRoot)
  13. }
  14. }, [shadowRoot])
  15. return (
  16. <div
  17. ref={hostRef}
  18. style={{
  19. flex: 1,
  20. display: 'flex',
  21. flexDirection: 'column',
  22. overflow: 'auto',
  23. }}
  24. >
  25. {shadowRoot ? createPortal(children, shadowRoot) : null}
  26. </div>
  27. )
  28. }