Get the Mouse Position (coordinates) in React

To get the Mouse position (coordinates) in React, Follow the below steps.

  1. Add addEventListener for mousemove event on the window object. 
  2. Access event object properties clientX and clientY in the event handler function to get the X and Y coordinates of the mouse pointer.

Here is an example.

import {useEffect, useState} from 'react';

export default function App(){
  	const [mouseCoordinates, setMouseCoordinates] = useState({x:0, y:0});
	
  	const mouseMoveHandler = (event) => {
    	setMouseCoordinates({
      		x:event.clientX,
      		y:event.clientY
    	});
  	}
  		
  	useEffect(()=>{
    	window.addEventListener('mousemove', mouseMoveHandler);
    	return(()=>{
      		window.removeEventListener('mousemove', mouseMoveHandler);
    	})
  	}, [])  
	
  	return (
    	<>
      		Mouse Coordinates: x = {mouseCoordinates.x}, y={mouseCoordinates.y}
    	</>
  	)
}

We added mousemove event to the window object using addEventListener() function inside a useEffect hook. Also, we are returning removeEventListener() from the useEffect to remove the mousemove event from the window object when the component gets unmounted. It is like a cleaning function. Read react doc for why the cleaning function is necessary.

When the user moves the cursor on the top of this element, mousemove event will be triggered and mouseMoveHandler() will get invoked. That means the event will be triggered when the cursor is within the bounds of that component.

Inside the mouseMoveHandler(), we have an event argument that has clientX and clientY properties. The clientX and clientY properties give the X-coordinate(horizontal coordinate) and Y-coordinate(vertical coordinate) of the mouse pointer position.

In the above example, we stored that x and y coordinate in a state mouseCoordinates and displayed in the view.

Get the mouse position (coordinates) relative to an element in React

To get the mouse position (coordinates) relative to an element in React, Follow the below steps.

  1. Add addEventListener for mousemove event on the window object. 
  2. The clientX and clientY properties of the event object in the event handler function give us the X and Y coordinates of the mouse pointer in global coordinates.
  3. Subtract the offsetLeft property of the event object from the clientX property to get the X position relative to the element. Similarly, subtract offsetTop property from the clientY property to get the relative Y position. 

See the below example.

import {useEffect, useState} from 'react';
export default function MyComponent(){

  const [mouseLocalCoordinates, setMouseLocalCoordinates] = useState({x:0, y:0});

  const mouseMoveHandler = (event) => {
    setMouseLocalCoordinates({
      x:event.clientX - event.target.offsetLeft,
      y:event.clientY - event.target.offsetTop
    });
  }

  useEffect(()=>{
    window.addEventListener('mousemove', mouseMoveHandler);
    return(()=>{
      window.removeEventListener('mousemove', mouseMoveHandler);
    })
  }, [])

  return (
    <>
      Mouse Local Coordinates: x = {mouseLocalCoordinates.x}, y={mouseLocalCoordinates.y}
    </>
  )
}

Apart from the previous example, here we subtracted event.target.offsetLeft from event.clientX to the x-coordinate related to the current element. The offsetLeft return number of pixels between the left position of the component and its parent. In the same way, we can calculate the Y-coordinate by subtracting event.target.offsetTop  from event.clientY. So after subtraction, our local coordinates will be (0, 0) when the pointer is at the top left position on the element.

Get the mouse position using npm package react-cursor-position

The react-cursor-position is an npm package that gives notification of cursor position changes. The mouse position coordinates are plotted relative to the components rendered by react-cursor-position.

Run the below command to install the react-cursor-position npm package.

npm install --save react-cursor-position

Next import ReactCursorPosition component from 'react-cursor-position'.

import MyComponent from "./MyComponent";
import ReactCursorPosition from 'react-cursor-position';

export default function App(){
  	return (
    	<>
      		<ReactCursorPosition>
        		<MyComponent></MyComponent>
      		</ReactCursorPosition>
    	</>
  	)
}

Wrap the components that need to access mouse position coordinates from the react-cursor-position library using ReactCursorPosition. All the child components of ReactCursorPosition component will receive the following props with information on element dimension, mouse pointer coordinates, and whether the pointer is outside of the element or not.

{
    detectedEnvironment: {
        isMouseDetected: false,
        isTouchDetected: false,
    },
    elementDimensions: {
        width: Number,
        height: Number
    },
    isActive: Boolean,
    isPositionOutside: Boolean,
    position: {
        x: Number,
        y: Number
    }
}

The detectedEnvironment is acquired from interaction with this component, So it will be unset until the user's first interaction on it. It returns isMouseDetected and isTouchDetected data.

elementDimensions:  It returns the width and height of the component in the number of pixels.

isPositionOutside: It returns true if the mouse pointer is within the bounds of the component( that means the top of the component). If the pointer is outside it returns false.

position: It returns the X-coordinates and Y-coordinates of the mouse pointer relative to that particular component. It returns the coordinates in the number of pixels.

By implementing mapChildProps API feature, the above structure can be modified.

In our example, we are displaying the mouse position coordinates in child components using these props.

export default function MyComponent(props){
  return <div>
    Mouse Local Coordinates: x = {props.position.x}, y={props.position.y}
  </div>;
}

Read more about react-cursor-position.

Conclusion

To get the Mouse position (coordinates) in React, use mousemove event and access event object properties clientX and clientY to get the X and Y coordinates of the mouse pointer on the window. If you want position relative to an element, then Subtract the offsetLeft and offsetTop properties of the event object from the clientX and clientY properties to get the X position and Y position relative to the element. Another option is to use the npm package react-cursor-position to get a notification of cursor position changes. It gives relative X and Y coordinates of that particular component.