Get the Mouse position (coordinates) in React

avatar

Borislav Hadzhiev

Last updated: May 3, 2022

banner

Photo from Unsplash

Get the Mouse position (coordinates) in React #

To get the mouse position in React:

  1. Set the onMouseMove prop on an element or add an event listener on the window object.
  2. Provide an event handler function.
  3. Access relevant properties on the event object.
App.js
import {useEffect, useState} from 'react'; export default function App() { const [coords, setCoords] = useState({x: 0, y: 0}); const [globalCoords, setGlobalCoords] = useState({x: 0, y: 0}); useEffect(() => { // 👇️ get global mouse coordinates const handleWindowMouseMove = event => { setGlobalCoords({ x: event.screenX, y: event.screenY, }); }; window.addEventListener('mousemove', handleWindowMouseMove); return () => { window.removeEventListener('mousemove', handleWindowMouseMove); }; }, []); const handleMouseMove = event => { setCoords({ x: event.clientX - event.target.offsetLeft, y: event.clientY - event.target.offsetTop, }); }; return ( <div> {/* 👇️ Get mouse coordinates relative to element */} <div onMouseMove={handleMouseMove} style={{padding: '3rem', backgroundColor: 'lightgray'}} > <h2> Coords: {coords.x} {coords.y} </h2> </div> <hr /> <h2> Global coords: {globalCoords.x} {globalCoords.y} </h2> </div> ); }

react get mouse position

The code sample shows how to handle the mousemove event on a div element or on the window object.

The mousemove event is triggered at an element when the user's mouse is moved while the cursor's hotspot is inside it.

To get the mouse coordinates relative to an element on the page, we had to subtract offsetLeft from clientX and offsetTop from clientY.

App.js
// 👇️ get mouse coords relative to the an element const handleMouseMove = event => { setCoords({ x: event.clientX - event.target.offsetLeft, y: event.clientY - event.target.offsetTop, }); };

The offsetLeft property returns the number of pixels that the upper left corner of the current element is offset to the left within the offsetParent node.

The offsetTop property returns the number of pixels between the outer border of the current element relative to the inner border of the closest positioned ancestor element.

The clientX property returns the horizontal coordinate within the application's viewport at which the event occurred.

And the clientY property returns the vertical coordinate within the application's viewport at which the event occurred.

The second example shows how to listen for the mousemove event on the window object to get the global mouse coordinates.

App.js
useEffect(() => { // 👇️ get global mouse coordinates const handleWindowMouseMove = event => { setGlobalCoords({ x: event.screenX, y: event.screenY, }); }; window.addEventListener('mousemove', handleWindowMouseMove); return () => { window.removeEventListener('mousemove', handleWindowMouseMove); }; }, []);

We passed an empty dependencies array to the useEffect hook because we only want to register the paste event listener once - when the component mounts.

The function we returned from the useEffect hook is called when the component unmounts.

We used the removeEventListener method to remove the event listener that we previously registered.

The cleanup step is important, because we want to make sure we don't have any memory leaks in our application.

The screenX property returns the horizontal coordinate (offset) of the mouse in global screen coordinates.

The screenY property returns the vertical coordinate (offset) of the mouse in global coordinates.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.