0

Why do we need to use var self = this;in render function? I think, this in render refers to my ServiceChooser component. Am I wrong? May somebody explain me that?

var ServiceChooser = React.createClass({

    getInitialState: function(){
        return { total: 0 };
    },

    addTotal: function( price ){
        this.setState( { total: this.state.total + price } );
    },

    render: function() {

        **var self = this;**

        var services = this.props.items.map(function(s){

            return <Service name={s.name} price={s.price} active={s.active} addTotal={self.addTotal} />;
        });

        return <div>
                    <h1>Our services</h1>

                    <div id="services">
                        {services}

                        <p id="total">Total <b>${this.state.total.toFixed(2)}</b></p>

                    </div>

                </div>;

    }
});
Lukas
  • 229
  • 3
  • 4
  • 10
  • `this` in `render`? - Yes. `this` in `map(function(s){`? - No – UnholySheep Jul 17 '17 at 19:36
  • 1
    See the linked question's answers for details. Basically, you're passing a `function` function into `map`. So `this` in that function is set by `map` when `map` calls it, and is not the same as `this` in `render`. Simplest solution in your case is to use an arrow function for the `map` callback and ditch the `self` variable. (Alternately, you could use `map`'s second argument, which lets you specify what to use as `this`. Or `Function#bind`. Etc. Again, see linked.) – T.J. Crowder Jul 17 '17 at 19:37

0 Answers0