Fred
Fred

Reputation: 649

ReactJS access "this" in a callback

Within a callback, I'd like to get the props passed to a component but can't get it through this.props as this is undefined there.

Here is a simplified example:

var MyComponent = React.createClass({  
  options:{
    componentFunction: function(c) {
      console.log(this.props.myProp); //this references to the options here, not the component itself 
    }
  },
  render: function() {
    return (
      <OtherComponent options={ this.options } />
    );
  }
});

And I pass the props this way:

<MyComponent myProp={"x"};

Would appreciate any help, Thanks.

Upvotes: 2

Views: 2725

Answers (2)

James Brierley
James Brierley

Reputation: 4670

The issue is that componentFunction has its own scope. You need to bind it, which you can do by adding the following method to MyComponent:

componentWillMount: function() {
    this.options.componentFunction = this.options.componentFunction.bind(this);
}

Update: If you're using ES6 classes, the above should go in the constructor instead.

However, it may be nicer to use arrow functions instead, which do not define their own scope and so will inherit this from the parent scope.

options:{
    componentFunction: () => console.log(this.props.myProp)
}

Upvotes: 4

Dmitriy Kovalenko
Dmitriy Kovalenko

Reputation: 3636

Use this.options.bind(this) instead of this.options to access this inside the function.

Or use ES6 syntax - options = () = {...}.

Upvotes: 2

Related Questions