Skip to content

Stitches 0.2 - insertionMethod alternative for dynamically created <iframe> and shadow DOM #628

@cpakken

Description

@cpakken

In Stitches 0.2, the insertionMethod is removed because of the transition to CSSOM. With that change, I propose some alternative API's that would grant the ability to initialize the root dom node dynamically / lazily.

  • Use stitches styled components within dynamically created iframes and shadow doms
  • can isolate styles using separate createCss() for different iframes / shadow doms

Taking a look at the source code for Stitches 0.2, It seems that createCss({root: DOCUMENT}) :
is an undocumented api for applying a custom root. However, this does not apply when the root is lazily / dynamically created.

Use Case

Building a chrome extension with UI overlay. A shadowdom/ iframe is dynamically created to separate css / dom implementation to avoid clashing.

Here are some API

Method 1: Similar to emotion's CacheProvider

//Emotion API for inspiration
<CacheProvider value={createCache({container: RootNode})}>
const { styled, RootProvider } = createCss({})

const Box = styled('div', {})

const IFrameExample = () => {
  const ref = useRef()

  return (
    <iframe ref={ref}>
      <RootProvider root={ref.current.contentWindow.document}>
        {/* Simplified for example, uses portals to insert components into body */}
        <Box>Example</Box>
      </RootProvider>
    </iframe>
  )
}

Method 2: Dynamically call initRoot

const { styled, initRoot } = createCss({})

const Box = styled('div', {})

const IFrameExample = () => {
  const ref = useRef()
  useEffect(() => initRoot(ref.current.contentWindow.document), [])

  return (
    <iframe ref={ref}>
      {/* Simplified for example, uses portals to insert components into body */}
      <Box>Example</Box>
    </iframe>
  )
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions