souporserious/restyle

client styles not applied deterministically

souporserious opened this issue · 1 comments

Client Component style are currently breaking when rendered after the initial load. For example, the following bug can be seen in mdxts where some styles are not being applied when the component is rendered on focus/hover:

image

Interestingly, the first code block on that page does work correctly and will inject the appropriate styles once it has been hovered. This seems to be a case where the cache may be incorrect for the first instance and following instances break.

The fix for this ended being to always render the generated style elements:

export const CopyButton = ({
  value,
  className,
  css: cssProp,
}: {
  value: string
  className?: string
  css?: CSSProp
}) => {
  const active = useContext(PreActiveContext)
  const [copied, setCopied] = useState(false)
  const [classNames, styleElements] = css({
    all: 'unset',
    ...cssProp,
  })

  if (active === false) {
-    return null
+    return styleElements
  }

  return (
    <button
      className={className ? `${className} ${classNames}` : classNames}
      onClick={() => {
        navigator.clipboard.writeText(value)
        setCopied(true)
        setTimeout(() => setCopied(false), 1000)
      }}
    >
      {copied ? 'Copied!' : 'Copy'}
      {styleElements}
    </button>
  )
}