Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding this to nested functions in React

How can I bind this to the React component when dealing with a nested function?

Here is a skeleton example. The reason that function2 is nested is so that you can get access to the variables defined in function1

class View extends Component{

    constructor(props){
        this.function1 = this.function1.bind(this);

        this.state = {
            a = null;
        }
    }

    componentDidMount(){
        function1();
    }

    function1(){
        console.log(this); //will show the component correctly

        var param1 = 10;

        //call a second function that's defined inside the first function
        function2();

        function function2(){
            console.log(this); //undefined

            var a = param1*2;

            this.setState({ a : a}); //won't work because this is undefined
        }
    }

    render(){
        return(
            <div>
                <p> Hello </p>
            </div>
        )
    }
}
like image 901
Badrush Avatar asked Dec 11 '22 08:12

Badrush


1 Answers

Why not just use arrow functions? That would make sure this is referenced properly. I am assuming you can use ES6.

function1 = () => {
    console.log(this);

    var param1 = 10;

    const function2 = () => {
      console.log(this);

      var a = param1*2;

      this.setState({ a }); 
    }

    function2(); // inkove the function
}

OR if you only want to use ES5, then this could also work

function1() {
    console.log(this);

    var param1 = 10;

    function function2() {
      console.log(this);

      var a = param1*2;

      this.setState({ a }); 
    }

    function2.bind(this)() // to invoke the function
}
like image 122
Nandu Kalidindi Avatar answered Dec 20 '22 17:12

Nandu Kalidindi