1

I am using the Konva API directly in my react componen, and it works perfectly.

I only have one big problem.

The problem is that when the component that contains the ref container is unmounted the react app crashes, saying that staging has no container anymore.

I have tried to call destroy on the stage when the component unmounts, it enters that method but it still crashes.

So basically, from what i understand, calling destroy on stage from within the react component does not destroy the stage from the DOM.

Could anyone help with this issue?

EDIT: adding code snippet

    export default class ReactComp extends Component {
     renderKonva(container) {

     var stage = new Konva.Stage({
       container: container,
       width: 500, 
       height: 350
     });
     var layer = new Konva.Layer();
     var rect = new Konva.Rect({
      stroke: '#155DA4',
      strokeWidth: 2,
      fill: '#fff',
      width: 190,
      height: 190,
      shadowColor: 'black',
      shadowBlur: 10,
      shadowOffset: [10, 10],
      shadowOpacity: 0.2,
      cornerRadius: 2,
      opacity: 0.75,
      visible: true
     });
     layer.add(rect);
     stage.add(layer);
    }

    render() {
      return (
       <div ref={ref => this.renderKonva(ref)}></div>
      )
    }

So whenever this component unmounts i get the error: "Uncaught Stage has no container. A container is required."

Also, i have tried calling destroy on the stage, but i still get the same error. Also, even if i create and destroy the stage in renderKonva, and in essence i will have nothing displayed, because stage was once created it throws the same error.

razvans
  • 3,172
  • 7
  • 22
  • 30

1 Answers1

1

renderKonva is a callbackRef. From the docs:

React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts.

That means, when it unmounts container is undefined.

So,

export default class ReactComp extends Component { 
 constructor(props){
  super(props)
  this.stage = null;
 }

 renderKonva(container) {
  if (!container) {
    this.stage.destroy();
    return;
  }

  var stage = new Konva.Stage({
   container: container,
   width: 500,
   height: 350
  });

  this.stage = stage;
  ...
 }

}

razvans
  • 3,172
  • 7
  • 22
  • 30