document.createElement does not work as expected in componentDidMount in React?

Viewed 670

I am trying to create a canvas element on the fly, in order to execute .toDataURL() method after I've done some drawing. But the document.createElement does not have the expected behavior.

When I try this:

componentDidMount() {
    var canvas = document.createElement('canvas');
    canvas.height = 100;
    canvas.width = 200;
    console.log(canvas);
}

I get in the console:

<canvas height="0" width="0"></canvas>

But using componentDidUpdate method works fine.

componentDidUpdate() {
    var canvas = document.createElement('canvas');
    canvas.height = 100;
    canvas.width = 200;
    console.log(canvas);
}
<canvas height="100" width="200"></canvas>

What exactly is happening here ?

Please any answers concerning the right way in React using either ref or applying <canvas /> element to DOM won't help me, as I am particularly trying to understand why there is this difference between componentDidMount and componentDidUpdate in React.

1 Answers

Ref is the proper way to target an element in React, and The proper way to creating an element in React returns them using jsx.

This example shows you how to make canvas:

const App = () => {

  const drawCanvas = (ref) => {
    if (ref) {
      ref.width = 200;
      ref.height = 100;
      const ctx = ref.getContext("2d");
      ctx.clearRect(0, 0, 200, 100);
      ctx.fillStyle = "grey";
      ctx.fillRect(0, 0, 200, 100);
    }
  };

  return <canvas ref={drawCanvas}/>
};

ReactDOM.render(<App />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Related