Skip to main content

Drag and drop canvas shapes

To enable drag&drop for any node on the canvas you just need to pass the draggable property into the component.

When you drag&drop a shape it is recommended to save its position into your app store. You can use the onDragMove and onDragEnd events for that purpose.

Drag bounds and React state

Konva changes the node's position directly during a drag. By default, React-Konva only applies props whose values changed between renders. If React state already contains y: 50, another state update with y: 50 will not reset the node's position.

For custom bounds or snapping, the handler must update the node directly, then save node.position() in state. The Simple Drag Bounds and Complex Drag and Drop demos use this approach. Alternatively, dragBoundFunc can constrain the node before Konva applies each drag position.

import React from 'react';
import { Stage, Layer, Text } from 'react-konva';

const App = () => {
const [isDragging, setIsDragging] = React.useState(false);
const [position, setPosition] = React.useState({
x: 50,
y: 50,
});

return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Text
text="Draggable Text"
x={position.x}
y={position.y}
draggable
fill={isDragging ? 'green' : 'black'}
onDragStart={() => {
setIsDragging(true);
}}
onDragEnd={(e) => {
setIsDragging(false);
setPosition({
x: e.target.x(),
y: e.target.y(),
});
}}
/>
</Layer>
</Stage>
);
};

export default App;