pmirnd pmirnd - 1 month ago 7
Javascript Question

use a function outside render method in reactjs

I have a code like this:

//my_file.js

var React = require('react');
var ReactDom = require('react-dom');
var App = React.createClass({
getInitialState:function(){
return {//something};
},
myFunction:function(html){
//some code
},
render:function(){
//some code
var someVar1, someVar2, someVar3;
someVar1.map( function(i, j){
someVar2.campos.map( function(k, j){
someVar3.campos.map( function(z, k){
this.myFunction(something);
}
}
}
return (
<div>
{ //something }
</div>
);
}
});
module.exports=App;


my_file.js:16 Uncaught TypeError: this.myFunction is not a function. What I'm doign wrong? How I use that function inside the render?

Answer

Problem is that in .map this refers to global scope not to your component. There are several ways how you can solve this problem

  1. set this for each .map

    someVar1.map( function(i, j){
      someVar2.campos.map( function(k, j){
        someVar3.campos.map( function(z, k){
          this.myFunction(something);
        }, this);
      }, this)
    }, this)
    
  2. store this in variable

    var self = this;
    someVar1.map( function(i, j){
      someVar2.campos.map( function(k, j){
        someVar3.campos.map( function(z, k){
          self.myFunction(something);
        });
      })
    })
    
  3. use arrow functions

    someVar1.map( (i, j) => {
      someVar2.campos.map( (k, j) => {
        someVar3.campos.map( (z, k) => {
          this.myFunction(something);
        });
      })
    })
    
Comments