Pass a Callback as Props - access methods via this.props?

Hi - I got the code to work but was a little confused.

The lesson says, " You pass methods to a child just like a regular prop. It’s assigned a name and you have access to that method name under this.props in the child component."

So I assumed that I would have to access the method this way:

<GetInput input = {this.state.inputValue} handleChange = {this.props.handleChange}>

Instead I had to change it to:
<GetInput input = {this.state.inputValue} handleChange = {this.handleChange}>

Is that contradictory or did I misunderstand something? This is my first time diving into React so that’s very likely.

Your code so far


class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ''
    }
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({
      inputValue: event.target.value
    });
  }

  render() {
    return (
       <div>
        { /* change code below this line */ }
        <GetInput input = {this.state.inputValue} handleChange = {this.props.handleChange}/>

        <RenderInput input = {this.state.inputValue}/>
        { /* change code above this line */ }
       </div>
    );
  }

};

class GetInput extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h3>Get Input:</h3>
        <input
          value={this.props.input}
          onChange={this.props.handleChange}/>
      </div>
    );
  }
};

class RenderInput extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h3>Input Render:</h3>
        <p>{this.props.input}</p>
      </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:

In the class MyApp, it will be referred to with just this because it is a member of that class. In GetInput, it will be referred to on this.props because it is being passed in on props.

The fact that they have the same name might be confusing you. You could have done:

<GetInput input = {this.state.inputValue} dealWithChange = {this.handleChange}>

There you would be passing in a variable on props called dealWithChange so it would be this.props.dealWithChange inside of GetInput, referring to whatever function was passed to it.

Yes, it gets confusing. Don’t worry, if you keep at it, it will gradually make sense. Just keep working with it.

1 Like