styled-components の特徴と Next.js のプロジェクトへstyled-componentsを導入するまでの手順
styled-components(スタイルドコンポーネント)
styled-componentsとは?
CSS in JSのライブラリでJSファイルの中にスタイルを記述して利用します。
ReactJSと相性が良くコンポーネント単位でスタイルを記述していくことができます。
公式サイト
styled-componentsを使うメリット
styled-componentsを利用するメリットはたくさんあると感じていますが
私が感じていることを簡潔にまとめています。
コンポーネント管理がしやすい
コンポーネントとスタイルを合わせて管理できるため管理が行いやすいです。
pages/index.tsxconst Title = styled.h1`
color: blue;
font-size: 50px;
`;
const Home = (): ReactElement => {
return <Title>Hello, world!</Title>;
};
このようにコンポーネントのファイルへスタイルを合わせて記述します。
スタイルが閉じられている
コンポーネントのスタイルは同じコンポーネントへしか当たりません。
任意のIDが割り振られ同じコンポーネントのみスタイルが当たるようになあります。
コンパイル後
php-template<style>
.bQcLNl {
color: blue;
font-size: 50px;
}
</style>
<h1 class="pages__Title-sc-16nru3a-0 bQcLNl">Hello, world!</h1>
スタイルの影響を防ぐためにBEPなどの複雑な命名規則を考える必要がありません。
CSSの文法をそのまま利用できる
オブジェクトではなくCSSの文法をそのまま利用できます。
pages/index.tsxconst Title = styled.h1`
color: blue;
font-size: 50px;
`;
それでは早速使っていきます。
環境
- Mac OS Big SUR 11.3.1
- yarn 1.22.10
- Node 14.15.3
- Next.js 10.2.3
- styled-components 5.3
ファイル操作で利用する Unix コマンドについて
基本的なディレクトリ作成やファイル操作は Unix コマンドを利用します。
Unix コマンドについて詳しくはこちらの記事を参考にしてください。
Next.js 環境の構築
前回Next.jsをインストールした環境の状態から変更を加えて行きます。
前回の記事については下記になりますので事前にご確認いただければと思います。
styled-componentsのインストール
styled-componentsのインストール
パッケージのインストール
プロジェクトディレクトリへ移動
前回作成したプロジェクトのディレクトリへ移動します。
terminalcd ~/next-sample
styled-components のインストール
yarn installコマンドでstyled-componentsをインストールします。
terminal$ yarn add styled-components
yarn add v1.22.10
// 中略
✨ Done in 4.67s.
関連パッケージのインストール
yarn installコマンドでbabel-plugin-styled-componentsと@types/styled-componentsをインストールします。
terminal$ yarn add -D babel-plugin-styled-components @types/styled-components
yarn add v1.22.10
info No lockfile found.
// 中略
success Saved lockfile.
success Saved 3 new dependencies.
info Direct dependencies
├─ @types/styled-components@5.1.10
└─ babel-plugin-styled-components@1.12.0
info All dependencies
├─ @types/hoist-non-react-statics@3.3.1
├─ @types/styled-components@5.1.10
└─ babel-plugin-styled-components@1.12.0
✨ Done in 4.71s.
@types/styled-components
styled-componentsの型定義ファイルになります。
babel-plugin-styled-components
styled-componentsのデバッグ系の設定を追加したり
SSRで利用できるようにするための設定を拡張するプラグインになります。
インストールしたパッケージの確認
package.jsonを開きインストールされたパッケージを確認します。
perl "dependencies": {
"next": "^10.2.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"styled-components": "^5.3.0"
},
"devDependencies": {
"@types/node": "^15.12.2",
"@types/react": "^17.0.11",
"@types/styled-components": "^5.1.10",
"babel-plugin-styled-components": "^1.12.0",
"typescript": "^4.3.2"
}
サンプルアプリの変更
前回作成したNext.jsのアプリケーションへ変更を加えていきます。
styled-componentsをNext.jsで使う設定
styled-componentsを利用できるようにするために
pages ディレクトリの直下に_document.tsxを作成します。
terminal$ vim ~/next-sample/pages/_document.tsx
下記内容を追記します。
_document.tsx
_document.tsximport 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()
}
}
}
_document.tsxとは
_document.tsx_はNext.jsで提供されているdocument系の定義をいこなうためのコンポーネントです。ここで定義した内容は通常のpages内のコンポーネントのページへアクセスがあった際にサーバー側のレンダリング時に呼ばれます。
index.tsxの変更
styled-componentsをインポートして
実際に使っていきます。
terminal$ vim ~/next-sample/pages/index.tsx
下記内容を追記します。
index.tsx
index.tsximport React, { ReactElement } from 'react';
import styled from 'styled-components';
const Title = styled.h1`
color: blue;
font-size: 50px;
`;
const Home = (): ReactElement => {
return <Title>Hello, world!</Title>;
};
export default Home;
.babelrcの設定追加
babelの設定ファイルである.babelrcを作成し設定内容を追記します。
terminal$ vim ~/next-sample/.babelrc
下記を追記します。
追記する内容
json{
"presets": ["next/babel"],
"plugins": [
[
"styled-components",
{ "ssr": true, "displayName": true }
]
]
}
ssr
サーバーサイドレンダリング時に利用できるようにします。
displayName
コンポーネントが書かれているファイル名をクラス名に出力することができます。
babelとは
JavaScriptのコードを変換するツールです。
次の世代のJavaScriptの標準機能をブラウザのサポートを待たずに使えるようにします。
Next.js アプリの起動
アプリケーションを起動させていきます。
起動コマンドの実行
yarn devコマンド実行します。
terminal$ yarn dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
// 中略
wait - compiling...
event - compiled successfully
コンソールへsuccessfullyと表示されたらアプリケーション起動は成功です。
ブラウザからアクセス
アプリケーションが起動したのでブラウザからアクセスしてみます。
http:localhost:3000へアクセスしてみてください。
青い色のHello, world!と表示が確認できます。
articleNext.js の キャッシュ無効化設計:タグ・パス・スケジュールの 3 軸でコントロール
articleNext.js Metadata API 逆引き:`robots`/`alternates`/`openGraph`/`twitter` の記入例
articleNext.js を Bun で動かす開発環境:起動速度・互換性・落とし穴
articleNext.js Edge Runtime vs Node Runtime:TTFB・コールドスタート・コストを実測検証
articleNext.js の Route Handlers で multipart/form-data が受け取れない問題の切り分け術
articleNext.js Server Components 時代のデータ取得戦略:fetch キャッシュと再検証の新常識
articleEmotion vs styled-components vs Stitches 徹底比較:DX/SSR/パフォーマンス実測
articleStorybook × Sass/Styled-Components で美しい UI 量産
articlestyled-components の特徴と Next.js のプロジェクトへstyled-componentsを導入するまでの手順
articleJavaScript 非同期エラー完全攻略:Unhandled Rejection を根絶する設計パターン
article【早見表】JavaScript MutationObserver & ResizeObserver 徹底活用:DOM 変化を正しく監視する
articleJavaScript Drag & Drop API 完全攻略:ファイルアップロード UI を最速で作る
articleJavaScript structuredClone 徹底検証:JSON 方式や cloneDeep との速度・互換比較
articleJavaScript 時刻の落とし穴大全:タイムゾーン/DST/うるう秒の実務対策
articleJavaScript Web Animations API:滑らかに動く UI を設計するための基本と実践
articleWebSocket Close コード早見表:正常終了・プロトコル違反・ポリシー違反の実務対応
articleStorybook 品質ゲート運用:Lighthouse/A11y/ビジュアル差分を PR で自動承認
articleWebRTC で高精細 1080p/4K 画面共有:contentHint「detail」と DPI 最適化
articleSolidJS フォーム設計の最適解:コントロール vs アンコントロールドの棲み分け
articleWebLLM 使い方入門:チャット UI を 100 行で実装するハンズオン
articleShell Script と Ansible/Make/Taskfile の比較:小規模自動化の最適解を検証
blogiPhone 17シリーズの発表!全モデルiPhone 16から進化したポイントを見やすく整理
blogGoogleストアから訂正案内!Pixel 10ポイント有効期限「1年」表示は誤りだった
blog【2025年8月】Googleストア「ストアポイント」は1年表記はミス?2年ルールとの整合性を検証
blogGoogleストアの注文キャンセルはなぜ起きる?Pixel 10購入前に知るべき注意点
blogPixcel 10シリーズの発表!全モデル Pixcel 9 から進化したポイントを見やすく整理
blogフロントエンドエンジニアの成長戦略:コーチングで最速スキルアップする方法
review今の自分に満足していますか?『持たざる者の逆襲 まだ何者でもない君へ』溝口勇児
reviewついに語られた業界の裏側!『フジテレビの正体』堀江貴文が描くテレビ局の本当の姿
review愛する勇気を持てば人生が変わる!『幸せになる勇気』岸見一郎・古賀史健のアドラー実践編で真の幸福を手に入れる
review週末を変えれば年収も変わる!『世界の一流は「休日」に何をしているのか』越川慎司の一流週末メソッド
review新しい自分に会いに行こう!『自分の変え方』村岡大樹の認知科学コーチングで人生リセット
review科学革命から AI 時代へ!『サピエンス全史 下巻』ユヴァル・ノア・ハラリが予見する人類の未来

