0

The issue I am having is that I am unable to call this.setState inside of the callback of an external library's method, and I also cannot bind to that method.

I am using a library called html2canvas, and I need to access the state of the class I'm using one of the methods in.

Here is my class:

class Test extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {

    html2canvas(document.getElementById("target"), {
        onrendered: function (canvas) {

          var base64image = canvas.toDataURL("image/png");
          document.body.appendChild(canvas);
          this.setState({canvas: canvas} );
        },
        width:320,
        height:220
    }).bind(this);
  }
}

This returns the following errors:

Inline Babel script:23 Uncaught TypeError: html2canvas(...).bind is not a function
    at Hello.componentDidMount (<anonymous>:22:8)
    at commitLifeCycles (react-dom.development.js:17469)
    at commitAllLifeCycles (react-dom.development.js:18871)
    at HTMLUnknownElement.callCallback (react-dom.development.js:143)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:193)
    at invokeGuardedCallback (react-dom.development.js:250)
    at commitRoot (react-dom.development.js:19083)
    at react-dom.development.js:20553
    at unstable_runWithPriority (react.development.js:735)
    at completeRoot (react-dom.development.js:20552)

which is on the .bind(this) call.

Inline Babel script:19 Uncaught TypeError: this.setState is not a function
    at Object.onrendered (<anonymous>:18:14)
    at Object.o.complete (html2canvas.min.js:8)
    at o (html2canvas.min.js:7)
    at Object.u.Preload (html2canvas.min.js:7)
    at html2canvas.min.js:8

You can view the example on the JSFiddle here: https://jsfiddle.net/michael_t/6q34ofws/125/

Kevin B
  • 94,570
  • 16
  • 163
  • 180
Michael
  • 3,093
  • 7
  • 39
  • 83

1 Answers1

3

The first issue is that you are using .bind(this) in the wrong place, it should be bound to the anonymous function that runs onrendered.

However, there is no need to bind this to the function, if you instead change to an arrow function so that your function does not bind this to itself but will refer to the Class.

html2canvas(document.getElementById("target"), {
     onrendered: (canvas) => {
          ...
          this.setState({canvas: canvas} );
        },
     ...
})
Einar Ólafsson
  • 3,036
  • 1
  • 19
  • 24