0

Someone too expert to explain me why "this" is linked to the App component (parent), according to me "this" is equal to the object that calls that method, in this case it would be "this.props" (this.props.parentCallback('something')) which makes no sense to me, I do not understand. I thought I understood "this" well, but I see that I didn't, I was overcome.

class App extends React.Component {
  state = {
    name: "",
  };

  handleCallback = (childData) => {
    this.setState({ name: childData });
  };

  render() {
    const { name } = this.state;
    return (
      <div>
        <Child parentCallback={this.handleCallback} />
        {name}
      </div>
    );
  }
}

class Child extends React.Component {
  onTrigger = (event) => {
    console.log(this.props);
    this.props.parentCallback(event.target.myname.value);
    event.preventDefault();
  };

  render() {
    return (
      <div>
        <form onSubmit={this.onTrigger}>
          <input type="text" name="myname" placeholder="Enter Name" />
          <br></br>
          <br></br>
          <input type="submit" value="Submit" />
          <br></br>
          <br></br>
        </form>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("app"));

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • I am a bit restless and want to see what is going on behind the scenes. –  Mar 06 '22 at 18:53
  • `handleCallback` is an arrow function, not a regular function. So it gets its value of `this` from how it's defined, not how it was called. – Nicholas Tower Mar 06 '22 at 18:53
  • thanks I think I read about that but, you mean, in this case "this" is already set as App from parentCallback={this.handleCallback} or like, I don't think I understand that yet. –  Mar 06 '22 at 19:05
  • The important code is `handleCallback = (childData) => { this.setState({ name: childData }); };` This code is a class field of `App`, so `this` is `App` when `handleCallback` is created, and it will still be `App` later, no matter how `handleCallback` is called. – Nicholas Tower Mar 06 '22 at 19:11
  • thank you very much sir, that is what I did not understand but now I understand it, God bless you –  Mar 06 '22 at 19:30

0 Answers0