LoginSignup
0
0

More than 1 year has passed since last update.

【React】「React children」を紐解く【children】

Posted at

はじめに

基本的な”props”や”コンポーネント”・”state”あたりは簡単に学習を済ませた私が、React.childrenで躓いたので使い方を確認しながら学ぶ記事です。

TL;DR

props.children:子要素の出力が可能

React.children:this.props.children を扱うためのユーティリティ(便利なもの)を提供するAPI

躓いた箇所

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}

上記のコードを見た時、
((FancyBorderにpropsとして渡してるのってcolorだけなのに、なんかprops.childrenって書いてる・・・え、どこからchildren来たの・・・?))
このように戸惑ってしまいました。

FancyBorderのprops.childrenに表示されるものは、こちら。
ポイントは、FancyBorderの子要素だということ。

<h1 className="Dialog-title">
  Welcome
</h1>
<p className="Dialog-message">
  Thank you for visiting our spacecraft!
</p>

Reactのchildrenとは

子要素を出力することができるpropsのこと。
https://ja.reactjs.org/docs/composition-vs-inheritance.html#containment(公式)

// 明示的に値を渡す必要が無い
<FancyBorder color="blue">

上記のように明示的にpropsへ値を渡さずとも、Reactが勝手に読み取ってくれます。

React.childrenって何?

childrenのことはよく理解できた!…と思いきや、調べていくと
props.childrenの他にReact.childrenを発見しました。
React.childrenとは何なのか、またどのように使用するのか見ていきます。

React.childrenとは

this.props.children を扱うためのユーティリティを提供するAPI
https://ja.reactjs.org/docs/react-api.html#reactchildren(公式)

私はこの公式の説明だけでは理解が出来なかったので、もう少し公式を読み進めてみます。
すると下記のような説明がありました。

  • React.Children.map
    this を thisArg に設定して、children 内に含まれるすべての直下の子要素に対して関数を呼び出す。
React.Children.map(children, function[(thisArg)])
  • React.Children.forEach
    [React.Children.map()](https://ja.reactjs.org/docs/react-api.html#reactchildrenmap) と似ているが、配列を返さない。
React.Children.forEach(children, function[(thisArg)])
  • React.Children.count
    children に含まれるコンポーネントの総数を返す。これは map または forEach に渡したコールバックが呼ばれる回数と同じ。
React.Children.count(children)

React.childrenは、取得した子要素をアレコレ操作することができる便利なAPIでした。

さいごに

React childrenを知ってから、Reactのコードを少し読みやすくなりました。
他にもたくさん分からない事があるので、一つずつ理解して、理想的なUIを作成していきたいと思います!

🙏参考リンク

https://ja.reactjs.org/docs/composition-vs-inheritance.html
https://ja.reactjs.org/docs/react-api.html#reactchildren

0
0
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
0