0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「children」って何?コンポーネントを挟む仕組みをサクッと理解する

0
Posted at

Reactを触っているとよく見かける、コンポーネントで別の要素を「挟む」書き方。これはchildrenという仕組みを使っています。

childrenを一言でいうと?

「共通の外枠」の中に「自由な中身」を流し込むための穴のことです。

基本の書き方

コンポーネントをタグで挟むと、その中身が自動的に children という名前で渡されます。

呼び出す側:

<Card>
  <p>Hello!</p> {/* これが children になる */}
</Card>

受け取る側(Card.js):
引数で { children } を受け取って、表示したい場所に置くだけです。

const Card = ({ children }) => {
  return <div className="card-style">{children}</div>;
};

なぜ使うのか?

一番の理由は、**「見た目や枠組みの使い回し」**ができるからです。

例えば「モーダル(ポップアップ)」の場合、大抵は「外枠(背景を暗くする、中央に白枠を出す)で、「中身」だけが違います。

childrenを使わない場合

中身が変わるたびに、if (type === 'form') のような条件分岐を「外枠コンポーネント」の中に書く必要があり、コードがどんどん複雑になります。

childrenを使う場合

外枠(Modal)は1つ作っておけば、あとは中身を自由に入れ替えるだけです。

// 1. お問い合わせ用
<Modal>
  <ContactForm />
</Modal>

// 2. 完了メッセージ用
<Modal>
  <p>送信が完了しました!</p>
</Modal>

補足:複数の要素を渡すとき

中身が複数のタグになる場合は、Reactのルール通り Fragment<> </>)で囲ってあげればOKです。

<Modal>
  <>
    <h2>タイトル</h2>
    <p>本文です</p>
  </>
</Modal>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?