13

This is a follow up to my previous question, but how do I call a function inside React's render() method, if I have a map inside that.

Example (this code is inside a class that extends React.Component):

getItemInfo(item){
  return `${item.Something} ${item.SomethingElse}`
}

render() {

return (
 <div className="someDiv">
    {
      collection.map(function (item) {
        return <div> {item.Name} {this.getItemInfo(item)} </div>
    })
  }
 </div>
);

}

No matter what I try I always end up getting "this.getItemInfo() is not a function".

I did a console.log on this inside my map() function and it was infact refering to the Window object, but I can't seem to find a way to change that.

I tired:

  • defining getItemInfo as function getItemInfo(){..}
  • passing this as a second parameter to my map function
  • calling this.getItemInfo = this.getItemInfo.bind(this) in react's component constructor
  • calling .bind(this) after getItemInfo(item)

And a couple other things....

None worked. I am fairly new to JavaScript's this reference, and I cant seem to figure it out.

I read some answers here related to using this inside render() but none of them seemed to work for me.

0

1 Answer 1

27
collection.map(function (item) {
    return <div> {item.Name} {this.getItemInfo(item)} </div>
})

So, the scope of this inside your function(item) is not the scope of your React Component.

If you use arrow function () => {...} instead of function() {...} you will have access to this of React.Component.

Try this

collection.map((item) => (
   <div> {item.Name} {this.getItemInfo.call(this, item)} </div>
))

To read more about scope of this in javascript, you can read here: http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/

To read about arrow functions and scope of this, refer to "No separate this " section of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Sign up to request clarification or add additional context in comments.

4 Comments

Hmm, this still says this.getItemInfo() is not a function. do I have to do anything special to my function declaration in order to get it to work
Hey, I have updated the answer with this.getItemInfo.call(this, item). If you use this.func() inside render(), you need to bind it.
Just tried it. I now get cannot read property of undefined :(
Edit: I manged to get it work. I had an inner .map(function) that I also needed to change. Thank you for the detailed answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.