Andre Pena
Andre Pena

Reputation: 59336

How to use "this" in a function passed as a "prop" to a subcomponent?

I'm using ReactJS.

I have a component that renders a subcomponent, I'm passing a function as a prop. However, I can't use this in the function handler.

var MyComponent = React.createClass({
    onChildStatusChanged: function () {
        // this.state is undefined, of course, because this function hasn't been called from this object context.
    },
    render: function() {
        return <div>
            <SubComponent onStatusChanged={this.onChildStatusChanged} />
        </div>
    }

How can I use this in the onChildStatusChanged?

Upvotes: 0

Views: 101

Answers (1)

Jamie Dixon
Jamie Dixon

Reputation: 53991

You can bind the current this context to the this.onChildStatusChanged function using bind.

this.onChildStatusChanged.bind(this)

The bind function will return a function equal to onChildStatusChanged but with the this context set to the one you specify.

bind is an ES5 feature so if you're targeting systems < ES5 you'll need to polyfil this function.

Update

You add the bind in your current event assignment:

<SubComponent onStatusChanged={this.onChildStatusChanged.bind(this)} />

Upvotes: 5

Related Questions