本記事ではReactとEmotionを組み合わせてReactアプリケーションのコンポーネントのスタイリング方法を解説します。
Emotionとは
EmotionはCSS in JSのフレームワークで、JSファイルの中にcssを記述することを可能にします。
Reactとの親和性があると巷で言われています。
https://emotion.sh/docs/@emotion/react
環境構築
以下の手順で環境構築をします
Reactプロジェクトの作成
create-react-app
コマンドを使用してReactプロジェクトを作成します。
1 2 |
npx create-react-app react-emotion cd react-emotion |
必要なパッケージのインストール
Emotionをプロジェクトに追加するために、以下のコマンドを実行します。
1 |
yarn add @emotion/react @emotion/styled |
これにより、@emotion/react
と@emotion/styled
の2つのパッケージがインストールされます。
基本的な使い方
ReactとEmotionを組み合わせる方法はいくつかありますが。ここでは@emotion/react
と@emotion/styled
を使った方法について紹介します。
@emotion/react
を使ったスタイリング
@emotion/react
を使ったスタイリングをするにはcss
関数をインポートし、それを使ってスタイルを定義します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** @jsxImportSource @emotion/react */ import { css } from '@emotion/react'; const ExampleComponent = () => { const styles = css` background-color: #f0f0f0; padding: 16px; border-radius: 4px; ` return ( <div css={styles}> Emotionスタイリングの例 </div> ) } export default ExampleComponent |
注意点としてcss
をインポートするコンポーネントでは先頭に/** @jsxImportSource @emotion/react */
とコメントアウトをする必要があります。
App.jsを以下のように編集します。
1 2 3 4 5 6 7 8 9 10 11 12 |
import ExampleComponent from './components/ExampleComponent'; import './App.css'; function App() { return ( <div className="App"> <ExampleComponent /> </div> ); } export default App; |
@emotion/styled
を使ったスタイリング
@emotion/styled
を使ってスタイリングするには、まずstyled
関数をインポートします。
それを使ってスタイル付きのコンポーネントを作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/** @jsxImportSource @emotion/react */ import styled from "@emotion/styled"; const StyledButton = styled.button` background-color: #007bff; border: none; border-radius: 4px; color: white; padding: 8px 16px; font-size: 16px; cursor: pointer; &:hover { background-color: #0056b3; } ` const ExampleButton = () => { return ( <StyledButton>クリックしてください</StyledButton> ) } export default ExampleButton |