1

I'm enjoying learning about KonvaJS with react and typescript.

I have a click handler on component that will create a new star at the x and y coordinates where it was clicked. It does this by adding the x and y coords to state.

That coord array is mapped over which renders the stars in the layer.

What I want to know is for recommended ways for the Stage component to know whether a blank space has been clicked or if a star has been clicked.

If a star has been clicked I want to remove it from state, but currently the stage is adding a new star there.

Is there a way for a child component, a star, to communicate up to its grandparent, the stage, letting it know it has been clicked, and therefore remove this star, not add another?

Charlie Wallace
  • 1,810
  • 1
  • 15
  • 17
risingBirdSong
  • 198
  • 3
  • 9

1 Answers1

2

You could check the target of the click, using a function similar to that posted below, and check an attribute on that target. If it matches, call remove on it. Otherwise, add a new star.

    stage.on('click', function (e) {
        
            console.log(e.target)
            
            if(e.target.attrs.name === "star") //this would require you adding a name: "star" attribute to all star objects, but could be done another way
            {
                //code to remove star
            }
            else {
                //code to add star
            }
        });
  • note, i cancelled event bubbling so that when a child is clicked, the stage isn't aware of it. With bubbling on, both the stage and child events fire separately. https://konvajs.org/docs/events/Cancel_Propagation.html – risingBirdSong Jun 30 '20 at 03:24