1

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?

taha maatof
  • 1,862
  • 2
  • 9
  • 23

1 Answers1

1

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/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.16.6/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>
jsejcksn
  • 27,667
  • 4
  • 38
  • 62