Search code examples
reactjskonvajsreact-konvakonvakonvajs-reactjs

Delete function bug on a node using React-Konva


So I have updated my previous react-konva example code with my latest problem: https://codesandbox.io/s/react-konva-drag-and-drop-image-with-delete-button-on-tranform-6977j?file=/src/Draganddrop.js

I am trying to add a delete button to every image that is visible when selected and when clicked removes the image that's selected from the stage and from the images array which I will eventually use to save and load state. I have managed to add the red circle and get it functioning as a delete button, but I cannot seem to move it to the top right of each image or add a white cross to the centre of the red circle.

The delete function itself removes the selected image from the images array and removes the node from the stage, but sometimes seems to remove multiple images from the stage even though it only ever removes the selected one from the array. I need it to only remove the one that is selected from the stage, I am current using UseRef to identify it, am i doing this wrong is there a better way to ensure it just removes the selected image?


Solution

  • You should rewrite this part of your code:

    const onDeleteImage = (node) => {
        const newImages = [...images];
        newImages.splice(node.index, 1);
        setImages(newImages);
    };
    

    Try not to use Konva instances when working with your state. node.index may be not equal to index of your image from the state. Because you may have many elements on the canvas, not just images (as in your example, you also have transformer). It effects Konva indexes. Instead, you should use your indexes from the state;

    const onDeleteImage = (index) => {
        const newImages = [...images];
        newImages.splice(index, 1);
        setImages(newImages);
    };
    
    // in jsx
    {images.map((image, index) => {
      return (
        <URLImage
          onDelete={() => onDeleteImage(index)}
        />
      );
    })}