Sourabh Banka
Sourabh Banka

Reputation: 1117

onMouseMove doesnot work outside of element react

I have an svg element on which I am doing onMouseDown, OnMouseMove and onMouseUp. My problem is that as soon as the user leaves the element while still holding their mouse button down, it does not register the mousemove. I want to keep the onMouseMove event on even after user leaves the element.

Here is my code:

Class School extents React.Component {
  onDragStartCircle = (e) {
    //taking the initial state
  }
  onDragCircle = () {
   // draging the element
  }
  onDragEndCircle = () {
    // saving data to the database
  }
  render() {
    return (
      <div>
        <svg>
          <circle
            cx={50}
            cy={50}
            r={10} 
            fill="red"
            onMouseDown={this.onDragStartCircle}
            onMouseMove={this.onDragCircle}
            onMouseUp={this.onDragEndCircle}
           />
        </svg>
      </div>
    );
  }
}

I have also tried onDragStart, onDrag these are not working. I am using es6.

Upvotes: 0

Views: 17010

Answers (1)

Hinrich
Hinrich

Reputation: 13983

Here is an example of your code, whichs shows how to use a container to register events outside of that circle.

You should consider subscribing to the move event on drag start, and unsubscribing again on drag end, to prevent to much events firing. But this should get you started.

class School extends React.Component {
  onDragStartCircle = (e) => {
    console.log('drag start')
  }
  onDragCircle = () => {
   console.log('move')
  }
  onDragEndCircle = () => {
    console.log('drag end')
  }
  render() {
    return (
      <div class="container" 
        onMouseMove={this.onDragCircle}
        onMouseUp={this.onDragEndCircle}>
        <svg>
          <circle
            cx={50}
            cy={50}
            r={10} 
            fill="red"
            onMouseDown={this.onDragStartCircle}
            
           />
        </svg>
      </div>
    );
  }
}


ReactDOM.render(
  <School />,
  document.getElementById("react")
);
.container {
  width: 100%;
  height: 100%;
}
<div id="react"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Upvotes: 2

Related Questions