はじめに
Reactのスタイルの扱い方についてまとめてみました。私のプロジェクトではCSS Modulesを使うことが多いです。CSS Modulesは、今までのCSSの書き方と同じように書くことができます。
Inline Style
Reactでも各タグにstyle属性を記述することで、スタイルの適用をすることができます。JavaScriptで記述するので、style={}のように波括弧で囲み、その中にオブジェクトでCSSに対応する要素を指定しているため、style={{}}
と記載します。
App.jsx
//文字を赤色に変更
export const App = () => {
return (
<>
<h1 style={{ color: "red" }}>こんにちは</h1>
</>
);
};
index.html
import ReactDom from "react-dom";
import { App } from "./App";
ReactDom.render(<App />, document.getElementById("root"));
事前に定義する場合
App.jsx
const contentStyle = {
color: "blue",
fontSize: "100px",
};
return (
<>
{console.log("a")}
<h1 style={{ color: "red" }}>こんにちは</h1>
<p style={contentStyle}>よろしくおねがいします。</p>
</>
);
};
index.html
import ReactDom from "react-dom";
import { App } from "./App";
ReactDom.render(<App />, document.getElementById("root"));
CSS Modulesを使う場合
はじめにパッケージをインストールします。私の環境がnode14なので、node14に対応したnode-sass
を入れます。
terminal
$ node -v
v14.17.6
$ yarn add node-sass@4.14.1
.module.scssという拡張子で、CSSファイルを作成します。
CssModules.module.scss
.title {
margin: 0;
color: red;
}
.button {
background-color: #ddd;
border: none;
padding: 8px;
border-radius: 8px;
&:hover {
background-color: #aaa;
color: blue;
cursor: pointer;
}
}
使うコンポーネントでimportします。
CssModules.module
import classes from "./CssModules.module.scss";
export const CssModules = () => {
return (
<>
<p className={classes.title}>CSS Modulesです</p>
<button className={classes.button}>ボタン</button>
</>
);
};