Reputation: 1117
Here is my svg code:
import React from 'react';
import ReactDOM from 'react-dom';
class DragArea extends React.Component {
state = {
viewWidth: 800,
viewHeight: 1000,
gridSize: 40,
vbox: {
x: 0,
y: 0,
w: 800,
h: 1000
},
dragAreaWidth: this.props.width * 40,
dragAreaHeight: this.props.length * 40
}
onmousedown = () => {return false;}
ondragdstart = () => {return false;}
componentDidMount() {
let viewHeight = parseInt(Math.max(window.innerHeight - this.dragAreaLayoutContainer.getBoundingClientRect().top - 50, 400));
let viewWidth = parseInt(Math.max(window.innerWidth - this.dragAreaLayoutContainer.getBoundingClientRect().left - 10, 320));
this.updateSVGDimensions(viewHeight, viewWidth);
}
updateSVGDimensions(viewHeight, viewWidth) {
this.setState({ viewHeight: viewHeight, viewWidth: viewWidth, vbox: Object.assign({}, this.state.vbox , {w: viewWidth, h: viewHeight}) });
}
dragSvg(e) {
console.log(e);
}
render() {
return(
<div ref={(input) => {this.dragAreaLayoutContainer = input}}>
<svg version="1.1" width={this.state.viewWidth} height={this.state.viewHeight} viewBox={Object.values(this.state.vbox).join(" ")} draggable="false" onDragStart={this.ondragdstart} onMouseDown={this.onmousedown} onDrag={this.dragSvg}>
<defs>
<pattern x="0" y="0" width="40" height="40" viewBox="0 0 40 40" patternUnits="userSpaceOnUse">
<rect x="0" y="0" width="40" height="40" fill="#dbeef0" stroke="#9bcfd2" strokeWidth="0.4">
</rect>
</pattern>
<pattern x="0" y="0" width="200" height="200" viewBox="0 0 200 200" patternUnits="userSpaceOnUse">
<rect x="0" y="0" width="200" height="200" fill="url(#smallrect)" stroke="#9bcfd2" strokeWidth="1">
</rect>
</pattern>
</defs>
<rect x="0" y="0" width={this.state.dragAreaWidth} height={this.state.dragAreaHeight} fill="url(#bigrect)" id="bg" draggable="false" onDragStart={this.ondragdtart} onMouseDown={this.onmousedown}></rect>
<g></g>
</svg>
</div>
);
}
}
I have to move this svg in to the div container and also update the vBox value. I have tried onDrag, onMouseMove and some other event listener but none of them are working. Also I have to add drag and drop feature to this svg. So that user can drag various image and drop into the svg. Also user can move the drop images from one part of svg to other part of svg. How can I do it in react.
Upvotes: 1
Views: 6355
Reputation: 15587
SVG doesn't support drag events, so you'll need to use onMouseDown
and onMouseUp
events, and track isDragging
in state.
<circle
onMouseDown={handleDragStart}
onMouseUp={handleDragEnd}
/>
Simple example: https://codepen.io/techniq/pen/yVEeOx?editors=0010
Read more: http://www.petercollingridge.co.uk/tutorials/svg/interactive/dragging/
Ah, prev question: Html5 drag and drop on svg element
Upvotes: 3