0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【3分で読める】Reactで子コンポーネントの値を親コンポーネントで取得(親へ渡す)方法

Posted at

やりたいこと

atomic designなどでコンポーネントを設計をしているとmolecules(子)が保持しているstateをorganisms(親)から参照したい場合などがあるはずです。
そんな時にどのように子コンポーネントのstateを親コンポーネントから参照するかを今回は説明します。

親から子のstateを取得する流れ

  1. 親コンポーネントで子のstateを保持、更新するためのuseStateを定義する。
  2. 1で定義したset○○を使ってstateを更新する関数を作成する。
  3. 2で作成した関数を子にpropsとして渡す。
  4. 子コンポーネントで親から受け取った関数をbuttonタグなどで実行する。

コード

親コンポーネント

ParentComponent.jsx
import { useState } from 'react'
import ChildComponent from '../atoms/ChildComponent'

const ParentComponent: React.FC = () => {
  // 1.親コンポーネントで子のstateを保持、更新するためのuseStateを定義する。
  const [parentState, setParentState] = useState('initial parent state')

  // 2.1で定義したsetParentStateを使ってparentStateを更新する関数を作成する。
  const setState = (childState) => {
    setParentState(childState)
  }

  return (
    // 3.2で作成した関数を子にpropsとして渡す
    <>  
      <ChildComponent parentFunction={setState} />
      <button onClick={() => console.log(parentState)}>Show Parent State</button>
    </>
  )
}
export default ParentComponent

子コンポーネント

ChildComponent.jsx
import { useState } from 'react'

const ChildComponent: React.FC = ({ parentFunction }) => {
  const [childState, setChildState] = useState('initial child State')

  // 4.子コンポーネントで親から受け取った関数をbuttonタグなどで実行する。
  return <button onClick={() => parentFunction(childState)}>Set Parent State</button>
}
export default ChildComponent

補足

上記のコードの挙動を確認すると初回レンダリングされた状態でShow Parent Stateボタンをクリックするとコンソールにinitial parent stateと表示されますが、Set Parent Stateボタンをクリック後、再度Show Parent Stateボタンをクリックするとコンソールに子から渡されたinitial child Stateが表示されるはずです。

今回は子の値を親から参照することを目的とした記事のため、子のsetChildState関数は使わずに初期値のinitial child Stateを親に渡すだけでしたが、もちろん動的に子のstateは変わると思うので開発中のプロジェクトでは子のset○○を使用して動的に値を変更してみてください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?