Search code examples
konvajsreact-konvakonvajs-reactjs

React Konva change zIndex on drag


Hey so I have little drag and drop game written in React konva. My draggable piece looks like this (simplified for convenience

   return this.props.areas.map((area) => 
        <Image draggable=true 
            {...area.imageProps} 
            onDragStart={() => {...}} 
            onDragEnd={() => {...}} 
            onDragMove={() => {...}}/> ) 

I would like the piece that is currently being dragged to be the one on the highest layer (highest zIndex).

Problem is React-Konva does not support zIndexing, and seems to want you to enforce the zIndexing based on order in the render method.

My solution was to updated the reactState with a currentDragIndex

 ...<Image 
    onDragStart = {this.setState({currentDragIndex: area.index})} 
     />

Then I try to reorder in the render method. However this causes the drag event to be interrupted.

Anyone have a good solution to this?


Solution

  • If you have an array of some items, the simplest solution is to change that array, by moving the dragging node to the end of the array. In your render function you just need to draw items from the array.

    handleDragStart = e => {
        const id = e.target.name();
        const items = this.state.items.slice();
        const item = items.find(i => i.id === id);
        const index = items.indexOf(item);
        // remove from the list:
        items.splice(index, 1);
        // add to the top
        items.push(item);
        this.setState({
          items
        });
    };
    

    Demo: https://codesandbox.io/s/11j51wwm3