序章

Reactを使用すると、styleプロパティを使用してコンポーネントのスタイルを直接設定できます。 ほとんどの場合、styleプロップを使用してCSSプロパティのオブジェクトを渡すだけで十分です。

ただし、より要求の厳しいスタイリング機能が必要な状況では、emotionが解決策を提供できます。 emotionは、柔軟でパフォーマンスの高いCSS-in-JSライブラリです。 文字列とオブジェクトを受け入れ、デフォルトと拡張の変数をサポートし、追加のBabelプラグインを使用してインラインの子セレクターもサポートします。

この記事では、スタイリングに@emotion/reactおよび@emotion/styledパッケージを使用するReactアプリケーションを構築します。

前提条件

このチュートリアルを完了するには、次のものが必要です。

注:この記事では、以前はemotionおよびreact-emotionパッケージを推奨していました。 現在、いくつかのバージョンの後、@emotion/react@emotion/styledが最新のアプローチです。

このチュートリアルは、ノードv15.3.0、npm v7.4.0、react v17.0.1、@emotion/react v11.1.4、および@emotion/styledv11.0.0で検証されました。 。

ステップ1—プロジェクトの設定

create-react-app を使用してReactアプリを生成し、依存関係をインストールすることから始めます。

  1. npx create-react-app react-emotion-example

新しいプロジェクトディレクトリに移動します。

  1. cd react-emotion-example

次に、npmを介して@emotion/react@emotion/styledをインストールします。

  1. npm install @emotion-react@11.1.4 @emotion/styled@11.0.0

この時点で、@emotion/reactを使用した新しいReactプロジェクトが作成されます。

ステップ2—cssプロップを使用する

emotionは、ネストされたセレクターとメディアクエリを受け入れることができるcssプロップを提供します。 オブジェクトまたはタグ付きテンプレートリテラルをサポートできます。

コードエディタでApp.jsファイルを開き、cssプロップで<div>を使用するように変更します。

src / App.js
/** @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に通知します。

アプリケーションを実行します。

  1. 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コンポーネントを使用するように変更します。

src / App.js
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に再度アクセスし、コンテンツを次のコード行に置き換えます。

src / 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トピックページで演習やプログラミングプロジェクトを確認してください。