今回は、ReactでCSSを使う方法を学習していきます。
ReactのCSSスタイリングの方法
代表的な方法
- CSSクラス
- CSSモジュール
- CSS-in-JSライブラリ
- Tailwind CSS
CSSクラスを使う方法
別でスタイルシートを作成し、コンポーネント側で呼び出す方法
.todo {
color: red;
font-size: 18px;
}
import "../css/style.css"
const root = createRoot(document.getElementById("app")!);
root.render(<ItemList />);
CSSモジュール
※css-loaderが非推奨になる可能性がある
スタイルをモジュール化して、コンポーネントごとにスコープを分離する方法。
クラス名の衝突を防ぐことができるのが特徴
.price {
color: red;
font-size: 18px;
}
import styles from "./style.modules.css";
import * as React from "react";
type ItemProps = {
name: string;
price: string;
};
const Item: React.FC<ItemProps> = ({ name, price }) => {
return (
<div className={styles.price}>
<h2>{name}</h2>
<p>価格: {price}</p>
</div>
);
};
export default Item;
CSS-in-JSライブラリ
- JavaScript内にCSSを記述し、直接コンポーネントにスタイルする方法。
- スタイルのスコープが限定され、CSSクラスの衝突を防ぐ
- 代表的なライブラリには、Styled Components と emotion がある。
npm i styled-components @types/styled-components
import styled from "styled-components";
const StyledTask = styled.h2`
color: blue;
font-size: 20px;
`;
const Task: React.FC = () => {
return <StyledTask>宿題をする</StyledTask>;
};
Tailwind CSS
ユーティリティファーストのCSSフレームワーク
事前に用意されたクラス名を当てていくことで、サイトを構築できる。
- デフォルトの設定をカスタマイズ可能
- Buildサイズの削減が可能 → 使わないクラスは削除される
今回はTailwindを使っていきます
Tailwind CSS を PostCSS プラグインとしてインストールします。
webpack などのビルド ツールと統合する最もシームレスな方法とのことです。
npmパッケージの導入
npm i save-dev --save-exact tailwindcss postcss autoprefixer postcss-loader
- tailwindcss
- TailwindCSSの導入
- postcss
- CSSをプラグインで変換・最適化するツール
- autoprefixer
- CSSにベンダープレフィックスを自動追加するPostCSSのプラグイン
- postcss-loader
- WebpackでPostCSSを使うためのローダー
PostCSSの初期化
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
Tailwind CSSの初期化
html
, js
, ts
, tsx
の拡張で使用できるように設定します。
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{html,js,ts,tsx}"],
theme: {
extend: {},
},
plugins: [],
};
CSSファイルを作る
@tailwind base;
@tailwind components;
@tailwind utilities;
webpackの設定
- postcss-loader の設定を追加する
- entry で設定している index.tsx ファイルの中で、importするCSSファイルを指定します。
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: "./src/js/index.tsx",
output: {
path: `${__dirname}/docs/`,
filename: "js/bundle.js",
},
mode: "development",
devtool: "source-map",
devServer: {
static: {
directory: "./docs/",
},
watchFiles: ["src/**/*"],
},
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader"],
},
{
test: /(\.ts|\.tsx)$/,
use: "ts-loader",
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
new MiniCssExtractPlugin({
filename: "css/style.css",
}),
],
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
};
CSSファイルのインポート
import * as React from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";
import "../css/main.css";
// Reactコンポーネントをレンダリング
const root = createRoot(document.getElementById("app")!);
root.render(<App />);
これで、全ての設定が完了しました。
要素の className
属性にTailwindCSSのスタイルを付与することで、スタイリングすることができます。
<h1 className="text-5xl">見出し</h1>
PropsWithChildrenの概念について

CSSとは少し脱線しますが、PropsWithChildren
の概念について学習しました。
子要素の型定義はPropsWithChildrenが便利です
- children(タグの中身)を受け取る際に毎回 Props を書くのは面倒
- PropsWithChildren を使うことで、簡単に受け取れる
- 他のPropsとの併用も、もちろん可能!
PropsWithChildren の基本の使い方
import * as React from "react";
import { PropsWithChildren } from "react";
export const Heading1 = ({ children }: PropsWithChildren) => {
return <h1 className="text-5xl">{children}</h1>;
};
import * as React from "react";
import { Heading1 } from "./component/Heading";
export const App = () => {
return <Heading1>見出し</Heading1>;
};
他のPropsと併用する書き方
import * as React from "react";
import { PropsWithChildren } from "react";
// Propsの型を定義
type HeadingProps = {
color: "blue" | "red" | "green"; // プリセットされた色の選択
};
// PropsWithChildren と独自の Props を併用
export const Heading1 = ({ children, color }: PropsWithChildren<HeadingProps>) => {
return <h1 className={`heading-${color}`}>{children}</h1>;
};
import * as React from "react";
import { Heading1 } from "./component/Heading";
export const App = () => {
return (
<div>
<Heading1 color="blue">青い見出し</Heading1>
<Heading1 color="red">赤い見出し</Heading1>
<Heading1 color="green">緑の見出し</Heading1>
</div>
);
};
開発リポジトリ
感想
ReactでのCSSスタイルの方法を学習してきました。
TailwindCSSはこれまでも使っていたのですが、webpackからコンパイルする設定ができていなかったので、まとめて動作できる環境構築を学ぶことができました。
TailwindCSS を中心に学習してきたのですが、CSSを自分で書く方法をもう少しキャッチアップしたいと思います。