3

When I try to drag an svg rect like below it first selects any text on my page and then become draggable. How I can make it draggable initially?

<g
      onDragStart={this.onDragStart}
      onDrag={this.onDrag}
      onDragEnd={this.onDragEnd}>
   <rect></rect>
   <text>{text}</text>
</g>

I'm using React and here are a functions of my component:

  onDragStart = (event) => {
    this.setState({
      dx: event.clientX - this.state.x,
      dy: event.clientY - this.state.y
    });
  };

  onDrag = (event) => {
    this.setState({
      x: event.clientX - this.state.dx,
      y: event.clientY - this.state.dy
    });
  };

  onDragEnd = (event) => {
    this.setState({
      x: event.clientX - this.state.dx,
      y: event.clientY - this.state.dy
    });
  };
svnvav
  • 338
  • 1
  • 7
  • 16
  • 1
    It sounds like you're just talking about [this](https://stackoverflow.com/questions/826782/how-to-disable-text-selection-highlighting-using-css)? – Chris W. May 27 '17 at 17:23
  • @Chris W. , after adding .noselect class it actually doesn't select the text within rect, but it still seems like a selection (mouse cursor) and it's still undraggable before I don't select something out of svg. – svnvav May 27 '17 at 17:54
  • So, i've found that the problem isn't a text tag. It happens when I use rect. Notable, it works right with circle. – svnvav May 27 '17 at 18:09
  • Please provide a [MCVE] – Paul LeBeau May 27 '17 at 18:14

1 Answers1

1

It turned out, I should use onMouseDown, onMouseMove, onMouseOut and onMouseUp events adding a bool property 'active' in the component state. Now it works.

<g
  onMouseDown={this.onDragStart}
  onMouseMove={this.onDrag}
  onMouseOut={this.onDrag}
  onMouseUp={this.onDragEnd}>
   <rect></rect>
   <text>{text}</text>
</g>

  onDragStart = (event) => {
    this.setState({
      active: true,
      dx: event.clientX - this.state.x,
      dy: event.clientY - this.state.y
    });
  };

  onDrag = (event) => {
    if(this.state.active)
      this.setState({
        x: event.clientX - this.state.dx,
        y: event.clientY - this.state.dy
      });
  };

  onDragEnd = (event) => {
    this.setState({
      active: false,
      x: event.clientX - this.state.dx,
      y: event.clientY - this.state.dy
    });
  };
svnvav
  • 338
  • 1
  • 7
  • 16