getting mouse coordinates in React and jQuery

You can try this:

import React, { Component } from "react";

class ClassCursorPosition extends Component {
  constructor(props) {
    super(props);
    this.state = {
      x: 0,
      y: 0
    };
  }

  logMousePosition = e => {
    this.setState({
      x: e.clientX,
      y: e.clientY
    });
  };
  componentDidMount() {
    window.addEventListener("mousemove", this.logMousePosition);
  }
  render() {
    return (
      <div>
        X- {this.state.x} Y - {this.state.y}
      </div>
    );
  }
}

Actually there are three things you can consider, here I mention clientX, clientY you can search for pageX, pageY and secrrenX, screenY as well.

pageX, pageY => depends on mouse position according to page.( scrollable page)

screenX, screenY => depends on mouse position according to screen ( height and width of different screens)


As others have mentioned, the issue is that react has not rendered your component to the DOM when jQuery tries to attach the event listener.

You don't need jQuery to do this at all, a better approach is to use the React events:

class Application extends React.Component {
  constructor(props) {
    super(props);

    this.state = { x: 0, y: 0 };
  }

  _onMouseMove(e) {
    this.setState({ x: e.screenX, y: e.screenY });
  }

  render() {
    const { x, y } = this.state;
    return <div onMouseMove={this._onMouseMove.bind(this)}>
      <h1>Mouse coordinates: { x } { y }</h1>
    </div>;
  }
}

Example pen: https://codepen.io/CarlosEME/pen/XWWpVMp


This is almost exactly the same answer with Carlos Martinez but with functional component and hooks:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [coord, setCoord] = useState({ x: 0, y: 0 });
  const handleMouseMove = (e) => {
    setCoord({ x: e.screenX, y: e.screenY });
  };

  return (
    <div className="main" onMouseMove={handleMouseMove}>
      <h1>
        Mouse coordinates: {coord.x} {coord.y}
      </h1>
    </div>
  );
}

Link to codesandbox: https://codesandbox.io/s/github/artidata/mouse-coordinate