Jaakko Karhu Jaakko Karhu - 4 months ago 8
Javascript Question

How to avoid React component automatically binding 'this'?

I have a function like this:

obj = {
func: function() {
console.log(this);
}
}


It is passed to React component as a prop:

React.createElement(Component, {
funcAsProp: obj.func
}


Then called in a react component like this:

let Component = React.createClass({
displayName: 'Component',

clickHandler: function () {
this.props.funcAsProp();
},

render: function () {
return React.createElement('div', {
onClick: this.clickHandler
});
}
});


When calling like this the obj.func this is the Component. I still have some confusion over Javascript 'this' and React automatic binding. Is the context binded to obj.func by React or is this some fundamental Javascript thing I don't get here?

And if it is about automatic binding, how do I call the function without binding this?

Answer

You can set this before you pass obj.func to props., because func lost own context and uses React's component context

const obj = {
  name: 'obj, name',
  
  func: function () {
    console.log(this.name);
  }
};

let Component = React.createClass({
  displayName: 'Component',

  clickHandler: function () {
    this.props.funcAsProp();
  },

  render: function () {
    return React.createElement('div', {
      onClick: this.clickHandler
    }, 'Click');
  }
});

ReactDOM.render(
  React.createElement(Component, { funcAsProp: obj.func.bind(obj) }),
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

Comments