Ad

Pass Function From Parent To Child

- 1 answer

I'm a little weak in javascript. I'm inspiring myself from this answer to pass a function from parent to child in REACT and I'm having a little difficulty.

Could someone help me correct my code? Thanks!

var List = React.createClass({
  deleting: function(test){
    console.log(test);
  },
  render: function() {      
    var all = this.props.activities;
    var test = List.deleting;
    var list = all.map(function(a){
      return (<ListItem act={a} del={test}>);
    });

    return (
      <ul> {list}
      </ul>
    );
  }
});

var ListItem = React.createClass({
  deleting: function(e){
    this.props.del(e.target.parentNode.firstChild.innerHTML);
  },
  render: function(){
    return (
      <li key={this.props.act}>{this.props.act} 
        <div onClick={this.deleting}>X</div>
      </li> 
    );
  }
});

The error I get:

enter image description here

Ad

Answer

You need pass reference to method .deleting that is part of List Object, now you are trying pass var test = List.deleting; that is undefined. In order to this in .map, refers to List, you should set this for .map by yourself - to do that just pass (in our case it should be this because this in render method refers to List) second argument to .map, and pass to del= attribute reference to method this.deleting.

Also set key attribute for ListItem, and in React all tags must be closed - so add /> ( now you are getting error because you have not closed tag ListItem) in the end of ListItem tag

var List = React.createClass({
  deleting: function(test) {
    console.log(test);
  },

  render: function() {      
    var all = this.props.activities;
    var list = all.map(function(a) {
      return (<ListItem key={a} act={a} del={this.deleting} />);
    }, this);

    return <ul> {list} </ul>
  }
});

Example

Ad
source: stackoverflow.com
Ad