Swarna Vallabhaneni
Swarna Vallabhaneni

Reputation: 13

Unable to pass parent methods to child components in React

I have a child component (a submit button) that I want to put in the parent. I want the child to access the parent's method.

Child:

var SubmitButton = React.createClass({
  submitHandler: function(e) {
    e.preventDefault();
    this.props.submitHandler(e);
  },
  render: function() {
    return (
      <div className="Form--row">
        <button onClick={this.submitHandler}>Submit</button>
      </div>
    );
  }
});

Now, when I call the child like this, it works:

var Form = React.createClass({
  submitHandler: function(e) {
       // do something
  },

  render: function() {
    return(
      <div className={classNames}>
        <form action="" className="Form">
            <SubmitButton submitHandler={this.submitHandler}/>
        </form>
      </div>
    )
  }
});

But when I try to populate like this, it throws an error:

render: function(e) {
    return(
        <div className={classNames}>
            <form action="" className="Form">
              {this.props.map(function(input) {
                if (input.inputType == 'button') {
                  return <SubmitButton submitHandler={this.submitHandler}/>;
                }
              })
              }
            </form>
          </div>
  )
}

Error:

Uncaught TypeError: Cannot read property 'submitHandler' of undefined

I would like to make the second method work, so that I can populate a parent using random children. What am I doing wrong in the second snippet?

Upvotes: 1

Views: 966

Answers (1)

Sam Ternent
Sam Ternent

Reputation: 281

Your problem lies here:

{this.props.map(function(input) {
            if (input.inputType == 'button') {
              return <SubmitButton submitHandler={this.submitHandler}/>;
            }
          })

this is now in the scope of your function, not your component, so the method doesn't exist on the this object.

var that = this;

{this.props.map(function(input) {
            if (input.inputType == 'button') {
              return <SubmitButton submitHandler={that.submitHandler}/>;
            }
          })

You can assign the value of this to a variable outside of the function scope, and reference it that way.

I'd recommend reading up a bit more on the scope of this in Javascript.

Upvotes: 1

Related Questions