Styled Components ThemeProvider is undefined inside Dreis HTML component

@drcmda

Hello everyone, once again reaching out regarding a potential bug (or useage error on my part).

Pretty fringe case but it’s blocking me, so hopefully someone could let me know if they have any ideas.

Basically: Using styled-components ThemeProvider doesn’t work if the HTML is inside Dreis HTML component.

A simple sandbox can be seen here.

Any ideas?

Thanks so much, Kyle

PS. I forked another sandbox of mine so the description/thumbnail is incorrect

this is unfortunate but context does not work across renderers. you can forward them, either manually or if you have many and it becomes too much of a burden GitHub - pmndrs/drei: 🥉 useful helpers for react-three-fiber with all these solutions you will have to access the root context.

it gets even worse. html is also a separate renderer (or root, as in, in dev tools you would see as a separate entry). so you’re basically passing the context through 3 renderers.

1 Like

Yeah that works well, thanks mate

Solution code:

import { Canvas } from '@react-three/fiber'
import { Html, useContextBridge } from '@react-three/drei'
import styled, { css, ThemeContext } from 'styled-components'
import { useContext } from 'react'

const StyledParagraph = styled.p`
  color: blue;
`

const StyledParagraphViaTheme = styled.p`
  ${({ theme }) => css`
    color: ${theme.primaryRed};
  `}
`

export const App = () => {
  const ContextBridge = useContextBridge(ThemeContext)

  return (
    <>
      <StyledParagraph>Outside Drei HTML Component</StyledParagraph>
      <StyledParagraphViaTheme>Outside Drei HTML Component with theme</StyledParagraphViaTheme>
      <Canvas>
        <ContextBridge>
          <Scene />
        </ContextBridge>
      </Canvas>
    </>
  )
}

export const Scene = () => {
  const theme = useContext(ThemeContext)
  console.log('ABHI', theme)
  return (
    <>
      <Html position={[0, 0, -5]} transform center>
        <div>
          <StyledParagraph>Inside Drei HTML component</StyledParagraph>
          <StyledParagraphViaTheme theme={theme}>Inside Drei HTML Component with theme</StyledParagraphViaTheme>
        </div>
      </Html>
    </>
  )
}

don’t need it any longer, context works ootb thanks to GitHub - pmndrs/its-fine: 🐶🔥 A collection of escape hatches for React.