Home > database >  is it possible to get a state from child component in parent (React Hooks)?
is it possible to get a state from child component in parent (React Hooks)?

Time:12-25

just a curious question, if i have something like this:

        const Parent= () => {
            const info = `hey show this ${state}` //how can i get this state from child?
            return  <div>
                <Child />
                <iframe
                        srcDoc={info}
                        width="100%"
                        height="100%"
                    />
                </div>
        }
        export default Parent

        const Child= () => {
            const [state, setstate] = useState("");
            const onclick =()=>{setstate('state from child')}

            return  <div>
                        <button onClick={onclick}>click!</button>
                        <p>I am a {state}</p>
                    </div>
        }
        export default Child

how can i get this state from child?

CodePudding user response:

Yes, by storing the state in the parent and passing the setState function to the child:

<div id="root"></div><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">

const {useState} = React;

function Child (props) {
  return <button
    onClick={() => props.setValue(new Date().toLocaleString())}
  >Update value</button>;
}

function Parent () {
  const [dateStr, setDateStr] = useState(new Date().toLocaleString());

  return (
    <div>
      <h2>Date: {dateStr}</h2>
      <Child setValue={setDateStr} />
    </div>
  );
}

function Example () {
  return <Parent />;
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script>

  • Related