LoginSignup
0
0

Mantine UIをNext.js App Routerで使用したいよって話

Posted at

Mantine UI とは?

ReactのUIライブラリです。
有名どころだとMaterialUi , ChakraUI と似たようなやつです。 ←適当

特徴としては、

  • カスタマイズ性が高く種類か豊富

    • 120種類以上の豊富なコンポーネントがある
  • ドキュメントがわかりやすい

    • こんな感じで使いたいコンポーネントの使用方法だったり、Sizeや色などを選択してコードをそのまま持っていくこともできます
      スクリーンショット 2023-09-29 19.53.03.png
  • React-Hook-Formなどの別ライブラリの必要がない

    • Mantine/form自体がform関連のhookを提供しているのでそれを使えば簡単にフォームにバリデーションをつけれる

などなど、比較的独自のスタイルを当てる必要がない管理画面等ではとても使いやすいライブラリです。

問題

Mantine UI はCSS in JSのフレームワークであるEmotionを採用しています。
*Mantine v7 alpha ではEmotionを利用してないとのこと

現状App RouterではEmotionをサポートしてません。

なのでそのままだと使えないので、クライアントサイドでcss出力処理をするように指定してあげないといけないらしい。

対策

appディレクトリに以下のファイルを作成

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://reactjs.org/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>
  )
}

次にappディレクトリにあるlayoutを修正

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

はい、これでおしまいです。
上記の対応をしたらApp RouterでもManineUiが使えるようになるかと思います!

まとめ

今回追加した処理によってRSCを活用できなくなるのでApp Routerとの相性は悪そうですね。
まぁ、個人でお試しでApp RouterとMantine UIを使ってみたい!という方は試してみてくださいー!
質問やご指摘などありましたらコメントいただけると嬉しいです!

以上!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0