Reactのスタイリングに感情を使用する方法
序章
Reactを使用すると、style
プロパティを使用してコンポーネントのスタイルを直接設定できます。 ほとんどの場合、style
プロップを使用してCSSプロパティのオブジェクトを渡すだけで十分です。
ただし、より要求の厳しいスタイリング機能が必要な状況では、emotionが解決策を提供できます。 emotion
は、柔軟でパフォーマンスの高いCSS-in-JSライブラリです。 文字列とオブジェクトを受け入れ、デフォルトと拡張の変数をサポートし、追加のBabelプラグインを使用してインラインの子セレクターもサポートします。
この記事では、スタイリングに@emotion/react
および@emotion/styled
パッケージを使用するReactアプリケーションを構築します。
前提条件
このチュートリアルを完了するには、次のものが必要です。
- Node.jsのローカル開発環境。 Node.jsをインストールしてローカル開発環境を作成する方法に従ってください。
注:この記事では、以前はemotion
およびreact-emotion
パッケージを推奨していました。 現在、いくつかのバージョンの後、@emotion/react
と@emotion/styled
が最新のアプローチです。
このチュートリアルは、ノードv15.3.0、npm
v7.4.0、react
v17.0.1、@emotion/react
v11.1.4、および@emotion/styled
v11.0.0で検証されました。 。
ステップ1—プロジェクトの設定
create-react-app を使用してReactアプリを生成し、依存関係をインストールすることから始めます。
- npx create-react-app react-emotion-example
新しいプロジェクトディレクトリに移動します。
- cd react-emotion-example
次に、npm
を介して@emotion/react
と@emotion/styled
をインストールします。
- npm install @emotion-react@11.1.4 @emotion/styled@11.0.0
この時点で、@emotion/react
を使用した新しいReactプロジェクトが作成されます。
ステップ2—css
プロップを使用する
emotion
は、ネストされたセレクターとメディアクエリを受け入れることができるcss
プロップを提供します。 オブジェクトまたはタグ付きテンプレートリテラルをサポートできます。
コードエディタでApp.js
ファイルを開き、css
プロップで<div>
を使用するように変更します。
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
function App() {
return (
<div>
<div css={css({
margin: 10,
padding: 10,
backgroundColor: '#eee',
})}>
This is an example of <code>`css`</code> using an object.
</div>
<div css={css`
margin: 10px;
padding: 10px;
background-color: #eee;
`}>
This is an example of <code>`css`</code> using a tagged template literal.
</div>
</div>
);
}
export default App;
最初の例では、スタイルオブジェクトのプロパティと値を持つオブジェクトを使用しています。 2番目の例では、CSSルールを使用してタグ付きテンプレートリテラルを使用します。
注:このチュートリアルはCreate React App 4に依存しているため、 / ** @jsxImportSource @ emotion / react */を指定する必要があります。 このコメントは、自動ランタイムインポートをカスタマイズするようにBabelに通知します。
アプリケーションを実行します。
- npm start
ブラウザでアプリケーションを観察します。 これにより、margin
が10ピクセル、padding
が10ピクセル、背景色が灰色の2つの同一の<div>
が生成されます。
ステップ3—styled
コンポーネントの使用
emotion
は、要素を作成してスタイルを設定するためのstyled
コンポーネントもサポートしています。 また、オブジェクトまたはタグ付きテンプレートリテラルをサポートすることもできます。
h1
見出し要素を生成し、fg
(フォアグラウンド)プロパティを受け入れてbackground-color
およびcolor
:
const Heading = styled('h1')`
background-color: ${props => props.bg};
color: ${props => props.fg};
`;
このHeading
コンポーネントを使用すると、bg
およびfg
にカラー値を渡すことができます。
<Heading bg="#008f68" fg="#fae042">
Heading with a green background and yellow text.
</Heading>
コードエディタでApp.js
に再度アクセスし、styled
コンポーネントを使用するように変更します。
import styled from '@emotion/styled';
const Heading = styled('h1')`
background-color: ${props => props.bg};
color: ${props => props.fg};
`;
function App() {
return (
<div>
<Heading bg="#008f68" fg="#fae042">
Heading with a green background and yellow text.
</Heading>
</div>
);
}
export default App;
このコードは、緑の背景と黄色のテキストを持つh1
要素になります。
次に、Heading
コンポーネントを拡張し、withComponent
を使用してレンダリングされたテキストを変更するSubheading
コンポーネントについて考えてみます。
const Subheading = Heading.withComponent('h2');
h1
の見出しの代わりに、コンポーネントはh2
の見出しでレンダリングされます。
このコードは、デフォルトの色でh2
を生成します。
<Subheading>
Subheading with default colors.
</Subheading>
このコードは、薄緑色のテキストでh2
を生成します。
<Subheading fg="#6db65b">
Subheading with light green text.
</Subheading>
このコードは、背景が薄緑色のh2
を生成します。
<Subheading bg="#6db65b">
Subheading with light green background.
</Subheading>
文字列ではなくオブジェクトとしてスタイルを指定できます。
const Quote = styled('blockquote')(props => ({
fontSize: props.size,
}));
また、デフォルトスタイルのオブジェクトを含めることもできます。
const Cite = styled('cite')(
{
fontWeight: 100
},
props => ({
fontWeight: props.weight
})
);
これは、コンポーネントを使用するときにオプションで設定できます。
このコードは、デフォルトのfontWeight
値を使用します。
<Cite>
Citation with light text!
</Cite>
このコードは、デフォルトのfontWeight
値をオーバーライドするweight
プロップを提供します。
<Cite weight={700}>
Citation with heavy text!
</Cite>
emotion
を使用すると、!important
スタイルを指定できます。
const Footer = styled('footer')`
margin-top: 50px !important;
`;
このコードは、50ピクセルのmargin-top
を持つfooter
要素を生成します。
ステップ4—css
プロップとstyled
コンポーネントの使用
ここで、前の例で学んだことを振り返り、それらの概念を使用して、css
小道具とstyled
コンポーネントを使用するコンポーネントを構築します。
コードエディタでApp.js
に再度アクセスし、コンテンツを次のコード行に置き換えます。
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
import styled from '@emotion/styled';
const Heading = styled('h1')`
background-color: ${props => props.bg};
color: ${props => props.fg};
`;
const Subheading = Heading.withComponent('h2');
const Quote = styled('blockquote')(props => ({
fontSize: props.size
}));
const Cite = styled('cite')(
{
fontWeight: 100
},
props => ({
fontWeight: props.weight
})
);
const Footer = styled('footer')`
border-top: 1px solid #ccc;
color: #ccc;
margin-top: 50px !important;
padding-top: 20px;
`;
function App() {
return (
<div css={css`background: #ddd;`}>
<div css={css({ padding: 10 })}>
<Heading bg="#008f68" fg="#fae042">
Quotations
</Heading>
<Subheading fg="#6db65b">
For React Developers
</Subheading>
<Quote size={28}>
I built this with <code>`emotion/react`</code> and <code>`emotion/styled`</code>!
</Quote>
<Cite weight={700}>Sammy</Cite>
<Footer>Shark Facts</Footer>
</div>
</div>
);
}
export default App;
このコードは、css
小道具とstyled
コンポーネントを文字列とオブジェクトで利用します。 また、withComponent
を使用してstyled
コンポーネントを拡張し、styled
コンポーネントをデフォルト値でオーバーライドすることも利用します。
結論
この記事では、スタイリングに@emotion/react
および@emotion/styled
パッケージを使用するReactアプリケーションを作成しました。
Reactの詳細については、 React.js シリーズのコーディング方法をご覧になるか、Reactトピックページで演習やプログラミングプロジェクトを確認してください。