1

I am using Javascript and React to build a front end. I am not sure how to reference a method of the containing object:

     var RAttribute = React.createClass({

        loadAssignmentsForList: function(elem) {
                //other code
            },

            render: function() {
                    var assignmentsLoading = this.props.assignmentsLoading;
                    var lists = this.props.data.lists.map(function(elem) {
                       return (<li className='list-group-item grey'>
                         <div className='list-group'>
                           <RList key = {elem.name} data={elem}
                              assignmentsLoading={assignmentsLoading}
                              loadAssignmentsForList={this.loadAssignmentsForList(elem)}/>
                       </div>
                      </li>);
                    });
                    //other code
          }
       //other code
     });

I am trying to call loadAssignmentsForList from within render so I am using this.loadAssignmentsForList(elem). However, I get the following error.

Uncaught TypeError: Cannot read property 'loadAssignmentsForList' of undefined
bsky
  • 19,326
  • 49
  • 155
  • 270

1 Answers1

2

Bind .this to .map, this in .map does not refer to RAttribute object

var lists = this.props.data.lists.map(function(elem) {
   // your code             
}.bind(this));

or you can set this to .map through second argument, like this

var lists = this.props.data.lists.map(function(elem) {
   // your code             
}, this);

also, if you are using ES6 you can use arrow functions

var lists = this.props.data.lists.map((elem) => {
   // your code             
});
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144