🙃

chakra-uiで特定のコンポーネントを呼び出した時のみglobal styleを当てたい

2022/01/15に公開

app全体のglobal styleを当てたい場合はChakraProviderに渡すthemeに書けば良いけど、特定のコンポーネントを呼び出した時はどうすれば良いだろう?🤔
https://chakra-ui.com/docs/features/global-styles#how-it-works

emotionのGlobal Stylesを使う😙

chakraが依存しているemotionのGlobal Stylesを使えば特定のコンポーネントを呼び出した時のみのglobal styleを当てられる
https://emotion.sh/docs/globals

import { Global } from '@emotion/react'

export const MyComponentWithGlobalStyle = () => {
  return (
    <>
      <Global
        styles={{
          body: {
            overflow: 'hidden',
          },
        }}
      />
      <MyComponent />
    </>
  )
}

サードパーティ製コンポーネントが独自のcssに依存していてオーバーライドしたい場合やリプレイス中で使える

おまけ

keyに変数を使う場合
JavaScriptのオブジェクトのkeyに変数を使うのと同じ

import { Global } from '@emotion/react'

export const MyComponentWithGlobalStyle = () => {
  const id = 'myComponent'
  
  return (
    <>
      <Global
        styles={{
          [`#${id}`]: {
            backgroundColor: 'red',
            a: {
              color: 'blue'
            }
          },
        }}
      />
      <MyComponent id={id} />
    </>
  )
}
GitHubで編集を提案

Discussion