vercel / styled-jsx

Full CSS support for JSX without compromises
http://npmjs.com/styled-jsx
MIT License
7.65k stars 266 forks source link

Flushing styles from an external component library into next js #830

Closed fausanchez closed 1 year ago

fausanchez commented 1 year ago

Hi, i have a components library that uses styled-jsx to style the components.

In that library i have an export with this:

import React, { ReactElement } from 'react'
import flush, { flushToHTML } from 'styled-jsx/server'

export type FlushToReact = <T>(opts?: { nonce?: string }) => Array<ReactElement<T>>
export type FlushToHTML = (opts?: { nonce?: string }) => string

const CssBaseline: React.FC<React.PropsWithChildren<unknown>> = ({ children }) => {
  return (
    <>
      {children}
    </>
  )
}

type MemoCssBaselineComponent<P = {}> = React.NamedExoticComponent<P> & {
  flush: FlushToReact
  flushToHTML: FlushToHTML
}

const MemoCssBaseline = React.memo(CssBaseline) as MemoCssBaselineComponent<
  React.PropsWithChildren<unknown>
>
MemoCssBaseline.flush = flush
MemoCssBaseline.flushToHTML = flushToHTML

export default MemoCssBaseline

And then on Next i could do something like this:

import Document, { Html, Head, Main, NextScript, DocumentContext } from 'next/document'
import { CssBaseline } from '@library'

class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx)
    const styles = CssBaseline.flush()

    return {
      ...initialProps,
      styles: (
        <>
          {initialProps.styles}
          {styles}
        </>
      ),
    }
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

With that setup, my components are working as expected, but thats using version 4.0.1.

Is there any way of doing this but on version 5? I cant figure out how to do it from the documentation of the library

huozhi commented 1 year ago

We've updated the new approach in readme server rendering section, you can use that to approach the same thing.

Can also checkout nextjs beta docs - css-in-js section for usage in app dir