-1

I want to use the state of my child Component in my parent component in this example . what i want exactly to be able to do is this:

<Application onChange={(myVar)=>{console.log(myVar)}}/>
FrenchTechLead
  • 1,118
  • 3
  • 13
  • 20

1 Answers1

1

You're onChange is just a normal prop which you pass into your Application component. So if it's a function you can call it whenever you want. In this case, it makes more sense to call it when Application's state is updated. You can use the second parameter of setState function which is an optional callback function for this. But just make sure you onChange prop is defined and it's a function before you call it with any parameter which you want to pass.

class Application extends React.Component {
  constructor(props){
    super(props);
    this.state = {myVar:0};
    setInterval(()=>{
      this.setState( { myVar:this.state.myVar + 1 }, () => {
        if(this.props.onChange && typeof this.props.onChange === "function")
          this.props.onChange(this.state.myVar)
      } ); 
      }, 3000);
  }

  //.....

}

Updated Codepen: https://codepen.io/anon/pen/gWvKxa

Tharaka Wijebandara
  • 7,955
  • 1
  • 28
  • 49