かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

React JSX 親コンポーネントから子コンポーネントの子要素を出力したい

こんなの

function Label(props) {
  // label で表示する要素を親コンポーネントで指定したい!
  return (
    <label htmlFor={props.htmlFor}>{ ◯◯◯◯ }<label>
  );
}

function Input(props) {
  return (
    <>
      <Label htmlFor={props.id}>推し</Label>
      <input id={props.id} defaultValue={props.dafaultValue} />
    </> 
  );
}

<Label /> コンポーネントを別に作っておいて、子要素はHTMLみたいに指定したいみたいなやつ。

props.children を使う

コンポーネント<Component></Component> の間にある子要素は children というプロパティでコンポーネントに渡されるので、コンポーネント{props.children} で出力

function Label(props) {
  return (
    <label htmlFor={props.htmlFor}>{props.children}<label>
  );
}

function Input(props) {
  return (
    <>
      <Label htmlFor={props.id}>推し</Label>
      <input id={props.id} defaultValue={props.dafaultValue} />
    </> 
  );
}

<label for="id">推し</label> と表示される

スプレッド構文を使う

プロパティをスプレッド構文 ...コンポーネントのattributeに展開すると子要素 (props.children) も出力できるっぽい。

function Label(props) {
  return (
    <label {...props}>
  );
}

function Input(props) {
  return (
    <>
      <Label htmlFor={props.id}>推し</Label>
      <input id={props.id} defaultValue={props.dafaultValue} />
    </> 
  );
}

<Label> につけている htmlFor の様な attribute は attribute として出力され、子要素はこようそ <label for="id">推し</label> 出力される

スプレッド構文で子要素が出力できるので、children attribute に値を渡しても子要素として出力できた。

function Label(props) {
  return (
    <label children={props.children} /> 
  );
}
ポエム

コンポーネントの側だけ作っておけるの button とか label とかで汎用コンポーネント作っておくのに便利そう。

スプレッド構文で出力する方がコンポーネントがシンプルに見えるけど、ざっくり見た感じ React のドキュメントにスプレッド構文で子要素出力する方法見つけられなかったので、お作法的に良いのか判断できてない。


[参考]

ユーフォ最終楽章えもえものえもだったから読んで! (布教)