CSS-in-JS

Collect styles

In order to avoid FOUC (flash of unstyled content), CSS-in-JS tools usually need to collect the page's styles upon SSR and add the collected styles to the HTML. (So that the browser loads the styles early.)

For example:

// /pages/+onBeforeRenderHtml.js
 
import { collect } from 'my-css-in-js-tool'
 
export default pageContext => {
  pageContext.collectedStyles = collect()
}
// /pages/+onAfterRenderHtml.js
 
import { useConfig } from 'vike-react/useConfig' // or vike-vue / vike-solid
import { generateCSS } from 'my-css-in-js-tool'
 
export default pageContext => {
  const config = useConfig()
  const css = generateCSS(pageContext.collectedStyles)
  config({ Head: css })
}

See:

Without vike-{react,vue,solid}

You can collect and inject the page's styles inside your onRenderHtml() hook.

React example:

// /renderer/+onRenderHtml.jsx
 
import ReactDOMServer from 'react-dom/server'
import React from 'react'
import { escapeInject, dangerouslySkipEscape } from 'vike/server'
import { CssCollector } from 'some-css-in-js-tool'
 
export { onRenderHtml }
 
async function onRenderHtml(pageContext) {
  const { Page } = pageContext
  const page = <Page />
 
  const collect = new CssCollector()
 
  const pageHtml = ReactDOMServer.renderToString(collect(page))
 
  return escapeInject`<!DOCTYPE html>
    <html>
      <head>
        <style>${dangerouslySkipEscape(collect.getCSS())}</style>
      </head>
      <body>
        <div id="page-view">${dangerouslySkipEscape(pageHtml)}</div>
      </body>
    </html>`
}

Examples:

See also