pmiranda
pmiranda

Reputation: 8420

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?

Upvotes: 1

Views: 1255

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

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);
        });
      })
    })
    

Upvotes: 3

Related Questions