作成日: 2023-4-25
更新日: 2023-9-28
styled-componentsはCSS in JSの一種です。
JavaScriptフレームワークでのCSSの適用をシンプルに書くことができます。
元々styled-componentsは、ReactでのCSSによるスタイリングを追求した結果生まれたものです。
なのでReactアプリケーションとの親和性が非常に高いです。
具体的にstyled-componentsがもたらしてくれる恩恵としては以下があげられます。
Next.jsのversionは12以降を想定します。
コマンドでインストールを行う
$ npm install styled-components
TypeScriptのプロジェクトでは、styled-componentsの型をインストール
$ npm install --save-dev @types/styled-components
next.config.jsのファイルに以下を追加する
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
// 以下を追加
compiler: {
styledComponents: true,
},
}
module.exports = nextConfig
SSGの場合、これで動きます。
試しにNext.jsのデフォルトで設定されているGlobalStyleをstyled-componentsで適用させます。
global.cssの内容をコピーします。
.
├── README.md
├── jest.config.js
├── jest.setup.js
├── next-env.d.ts
├── package-lock.json
├── package.json
├── pages
│ ├── _app.tsx
│ ├── index.module.css
│ └── index.tsx
├── public
│ ├── favicon.ico
│ └── vercel.svg
├── styles
│ └── global.css // これ
├── tsconfig.json
└── types.d.ts
import type { AppProps } from 'next/app'
// import '@/styles/global.css' これを削除
// 以下をimport
import { createGlobalStyle } from 'styled-components'
// 中身は、global.cssの内容
const GrobalStyle = createGlobalStyle`
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
body {
color: white;
background: black;
}
}
`
function MyApp({ Component, pageProps }: AppProps) {
return (
<>
// コンポーネントを追加
<GrobalStyle />
<Component {...pageProps} />
</>
)
}
export default MyApp
Next.jsのSSRでレンダリングするページがある場合は、さらに追加で設定が必要です。
pages/_document.tsxを作成します。
import Document, { DocumentContext } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: [initialProps.styles, sheet.getStyleElement()],
}
} finally {
sheet.seal()
}
}
}
これでSSRのページでもstyled-componentsを利用することができます。
styled-componentsを導入することでCSSの取り扱いがかなり楽になります。
そのほかにも同様のCSS in JSの例としては、Tailwind CSSがあげられます。
DevHarryではTailwind CSSを使っていますが、正直、styled-componentsの方が使いやすいと思います。
Reactアプリケーションであれば、styled-componentsを使うことをお勧めします。