Skip to content

Emotion props の渡し方

Emotion は CSS-inJS ライブラリです。React や Next.js でスタイリングする際に、props を渡してその値に応じてスタイルを変化させる方法です。

Emotion の主なスタイリング方法である css Prop を使用する場合の props の渡し方です。

1. インストール

npm install @emotion/react

2. Title コンポーネントを用意する

見出しなどを表示する Title コンポーネントを例に進めます。

props としてタイトルの文字列( children )と textAlign を受け取ります。

Emotion の css Prop でスタイルも設定済みとします。

import { ReactElement, ReactNode } from "react";
import { css } from "@emotion/react";

interface TitleProps {
  children: ReactNode
  textAlign?: string
}

export const Title = ({ title, textAlign = "left" }: TitleProps): ReactElement => {
  return (
    <h1 css={titleStyle}>
      {children}
    </h1>
  );
};

const titleStyle = css`
  font-size: 2.4rem;
  font-weight: 700;
  letter-spacing: 0.05em;
  color: var(--color-primary);
`;

3. props を emotion css に渡す

css Prop を設定している箇所に、渡したい props を以下のように記述します。

<h1 css={titleStyle({ textAlign })}>

css Prop で設定しているスタイルで props を受け取ります。

const titleStyle = ({ textAlign }: { textAlign: string }) => css`
  font-size: 2.4rem;
  font-weight: 700;
  letter-spacing: 0.05em;
  color: var(--color-primary);
  text-align: ${textAlign};
`

コンポーネントを読み込む際に以下のように指定します。

{
  /* 左寄せ(デフォルト) */
}
<Title>Headline</Title>;

{
  /* 中央寄せ */
}
<Title textAlign="center">Headline</Title>;

{
  /* 右寄せ */
}
<Title textAlign="right">Headline</Title>;