コンテンツへスキップ

CSS-in-JS

警告: ランタイムJavaScriptを必要とするCSS-in-JSライブラリは、現在サーバーコンポーネントではサポートされていません。サーバーコンポーネントやストリーミングなどの新しいReact機能でCSS-in-JSを使用するには、ライブラリアーがコンカレントレンダリングを含むReactの最新バージョンをサポートする必要があります。

Reactチームと協力して、ReactサーバーコンポーネントとストリーミングアーキテクチャをサポートするCSSとJavaScriptアセットを処理するためのアップストリームAPIに取り組んでいます。

次のライブラリは、appディレクトリ(アルファベット順)のクライアントコンポーネントでサポートされています。

現在サポートに取り組んでいるもの

知っておくと良い点: さまざまなCSS-in-JSライブラリをテストしており、React 18の機能やappディレクトリをサポートするライブラリの例を追加していきます。

サーバーコンポーネントのスタイルを設定する場合は、CSS ModulesまたはCSSファイルを出力するその他のソリューション(PostCSSやTailwind CSSなど)の使用をお勧めします。

appでのCSS-in-JSの設定

CSS-in-JSの設定は、次の3つのステップからなるオプトインプロセスです。

  1. レンダリングですべてのCSSルールを収集するためのスタイルレジストリ
  2. ルールを使用する可能性のあるコンテンツの前にルールを挿入するための新しいuseServerInsertedHTMLフック。
  3. 初期サーバーサイドレンダリング中にスタイルレジストリでアプリをラップするクライアントコンポーネント。

styled-jsx

クライアントコンポーネントでstyled-jsxを使用するには、v5.1.0を使用する必要があります。まず、新しいレジストリを作成します。

app/registry.tsx
'use client'
 
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
 
export default function StyledJsxRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://react.dokyumento.jp/docs/hooks-reference.html#lazy-initial-state
  const [jsxStyleRegistry] = useState(() => createStyleRegistry())
 
  useServerInsertedHTML(() => {
    const styles = jsxStyleRegistry.styles()
    jsxStyleRegistry.flush()
    return <>{styles}</>
  })
 
  return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>
}

次に、ルートレイアウトをレジストリでラップします。

app/layout.tsx
import StyledJsxRegistry from './registry'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledJsxRegistry>{children}</StyledJsxRegistry>
      </body>
    </html>
  )
}

例はこちらをご覧ください.

スタイルコンポーネント

以下は、styled-components@6以降を設定する方法の例です。

まず、next.config.jsでstyled-componentsを有効にします。

next.config.js
module.exports = {
  compiler: {
    styledComponents: true,
  },
}

次に、styled-components APIを使用して、レンダリング中に生成されたすべてのCSSスタイルルールを収集するグローバルレジストリコンポーネントと、それらのルールを返す関数を作成します。その後、useServerInsertedHTMLフックを使用して、レジストリに収集されたスタイルをルートレイアウトの<head> HTMLタグに挿入します。

lib/registry.tsx
'use client'
 
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'
 
export default function StyledComponentsRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://react.dokyumento.jp/docs/hooks-reference.html#lazy-initial-state
  const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())
 
  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement()
    styledComponentsStyleSheet.instance.clearTag()
    return <>{styles}</>
  })
 
  if (typeof window !== 'undefined') return <>{children}</>
 
  return (
    <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
      {children}
    </StyleSheetManager>
  )
}

ルートレイアウトのchildrenをスタイルレジストリコンポーネントでラップします。

app/layout.tsx
import StyledComponentsRegistry from './lib/registry'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  )
}

例はこちらをご覧ください.

知っておくと良いこと:

  • サーバーレンダリング中、スタイルはグローバルレジストリに抽出され、HTMLの<head>にフラッシュされます。これにより、スタイルルールがそれらを使用する可能性のあるコンテンツの前に配置されます。将来、スタイルを挿入する場所を決定するために、今後のReact機能を使用する可能性があります。
  • ストリーミング中、各チャンクからのスタイルが収集され、既存のスタイルに追加されます。クライアントサイドのハイドレーションが完了すると、styled-componentsは通常どおり引き継ぎ、さらに動的なスタイルを挿入します。
  • スタイルレジストリにツリーの最上位レベルでクライアントコンポーネントを具体的に使用するのは、このようにCSSルールを抽出する方が効率的であるためです。後続のサーバーレンダリングでのスタイルの再生成を回避し、サーバーコンポーネントペイロードへの送信を防ぎます。
  • styled-componentsコンパイルの個々のプロパティを設定する必要がある高度なユースケースについては、Next.js styled-components APIリファレンスを参照して詳細をご覧ください。