styled-jsx

You can use Vike with styled-jsx.

Example:

To use Vike with styled-jsx:

  1. Install:

    npm install styled-jsx
  2. Add styled-jsx to vite.config.js:

    // vite.config.js
     
    import react from '@vitejs/plugin-react'
    import vike from 'vike/plugin'
     
    export default {
      plugins: [react({ babel: { plugins: ['styled-jsx/babel'] } }), vike()]
    }
  3. Collect and inject styles.

    When using a CSS-in-JS tool, like styled-jsx, you always need to collect the page's styles upon SSR in order to avoid FOUC.

    If you use vike-react/vike-vue/vike-solid, then see Integration > CSS Tools > Collect styles upon SSR.

    // /renderer/+onRenderHtml.js
     
    export { onRenderHtml }
     
    import React from 'react'
    import { renderToString, renderToStaticMarkup } from 'react-dom/server'
    import { escapeInject, dangerouslySkipEscape } from 'vike/server'
    import { Layout } from './Layout'
    import { createStyleRegistry, StyleRegistry } from 'styled-jsx'
     
    const registry = createStyleRegistry()
     
    async function onRenderHtml(pageContext) {
      // flush styles to support the possibility of concurrent rendering
      registry.flush()
     
      const { Page } = pageContext
      // include the styleregistry in the app render to inject the styles
      const viewHtml = dangerouslySkipEscape(
        renderToString(
          <StyleRegistry registry={registry}>
            <Layout>
              <Page />
            </Layout>
          </StyleRegistry>
        )
      )
     
      // extract the styles to add as head tags to the server markup
      const headTags = renderToStaticMarkup(<>{registry.styles()}</>)
     
      return escapeInject`<!DOCTYPE html>
        <html>
          <head>
            ${dangerouslySkipEscape(headTags)}
          </head>
          <body>
            <div id="page-view">${viewHtml}</div>
          </body>
        </html>`
    }

See also