0

I have created a class which renders a div to which I have connected some functions that get executed whenever the user starts clicking and dragging within the view (onMouseMove event). I have used the following code to do so:

class MouseMover extends React.Component {
  state = {
    x: 0,
    y: 0,
    open: false
  };

  handleMouseMove = e => {
    if (!this.state.open) {
      return
    }
    this.setState({
      x: e.clientX,
      y: e.clientY
    });
  };

  started = e => {
    this.setState({
      open: true
    });
  };

  ended = e => {
    this.setState({
      open: false
    });
  };

  render() {
    return (
      <div onPointerDownCapture={this.started} onPointerLeave={this.ended} onPointerUpCapture={this.ended} onMouseMove={this.handleMouseMove} className='gesture-view'>
        {this.state.x || this.state.y
          ? "The mouse is at x: " + this.state.x + ", y: " + this.state.y
          : "Move the mouse over this box"}
      </div>
    );
  }
}

The question I have relates to the x- and y-values (the position of the mouse as it drags). The positional values are relative to the entire visible screen. This means that when the user clicks and drags to the left end of the div, the x value will be 60, because I have a marginal of 5vw to the left. I would like to have the positional values relate to the div that the events are connected to. When the user clicks and drags to the left part of the div, the x value should move towards zero, not 60.

I am not sure that this is necessary information, but it might be worth to know that my App function, which I render into the DOM looks like this:

function App() {
  return (
    <div className="App">
      <MouseMover />
    </div>
  );
}

It is quite uncomplicated but I need to fix the issue before I proceed, since this is just a prototype.

0 Answers0