初めに
ReactでCSS-in-JSライブラリのEmotionを使用した時の忘備録を残します。
導入
まず、下記のコマンドを流し、npm installします。
npm i @emotion/react @emotion/styled
基本的には@emotion/reactだけでも問題ありません。
@emotion/styledはCSS-in-JSライブラリのstyle-componentsのような使い方をしたいときに入れれば良いかと思っております。
(違かったらすいません。)
サンプルコード
/** @jsxRuntime classic */
/** @jsx jsx */
import { jsx, css } from "@emotion/react";
import styled from "@emotion/styled";
export const Emotion = () => {
const container = css`
width: 50%;
border: solid 3px red;
border-radius: 40px;
padding: 8px;
margin: 0 auto;
display: flex;
justify-content: space-around;
align-items: center;
`;
const text = css({
fontWeight: "bold",
color: "blue",
});
return (
<div css={container}>
<p css={text}>Emotionの箱</p>
<Button>ボタン</Button>
</div>
);
};
const Button = styled.button`
border-radius: 40px;
background-color: khaki;
`;
画面はこんな感じ
解説
1,2行目
お作法的なもの。こちらを書かないとemotionはうまく動かない。
(ちなみにコメントアウトしても動いた。)
/** @jsxRuntime classic */
/** @jsx jsx */
7-21行目
const container = css`
width: 50%;
border: solid 3px red;
border-radius: 40px;
padding: 8px;
margin: 0 auto;
display: flex;
justify-content: space-around;
align-items: center;
`;
const text = css({
fontWeight: "bold",
color: "blue",
});
containerの方に関しては、css,scss記法を使用してスタイルを定義できます。
その場合cssの後に``で囲み記述していきます。
textの方に関してはオブジェクトを()で囲むような形になります。
そのため、CSSの書き方もキーはキャメルケースになっており、valueは文字列になっていることに注意してください。
23-28行目
jsxをreturnしているところ。
スタイルの当て方はcss=の後に定義したものを入れ込む形です。
return (
<div css={container}>
<p css={text}>Emotionの箱</p>
<Button>ボタン</Button>
</div>
);
31-34行目
こちらが@emotion/styledでインポートしたものを使った書き方です。
styled-componentsと同じような書き方ができ、
インポートした変数名.HTMLタグ名css,scss記法で定義できます。
こちらは先に書きましたが、ReactのComponentとして使用できるのでそのままjsxに埋め込めます。
const Button = styled.button`
border-radius: 40px;
background-color: khaki;
`;
終わり
簡単ですが、Reactでのemotionの導入でした。
自由な使い方がよさそうですが、自由度がきく分チーム開発では運用ルールを準備したいものかなと思いました。
