Documentation about using Vike with styled-jsx.

💚
This page is maintained by the community and may contain outdated information; PR welcome to update or improve it.

If you are using vike-react you can use vike-react-styled-jsx for automatic integration.

The vike-react-styled-jsx extension requires vike-react.

Manual integration

If you use vike-react, you can manually integrate styled-jsx by using:

Example:

Without vike-react

To use Vike with styled-jsx without vike-react:

  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.

    // /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>`
    }

Example:

See also