Get the Mouse position (coordinates) in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
3 min

banner

# Table of Contents

  1. Get the Mouse position (coordinates) in React
  2. Get the Mouse position relative to an element in React

# 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}); useEffect(() => { const handleWindowMouseMove = event => { setCoords({ x: event.clientX, y: event.clientY, }); }; window.addEventListener('mousemove', handleWindowMouseMove); return () => { window.removeEventListener( 'mousemove', handleWindowMouseMove, ); }; }, []); return ( <div> <p> Mouse positioned at:{' '} <b> ({coords.x}, {coords.y}) </b> </p> </div> ); }

react get mouse position

The code for this article is available on GitHub

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

We used the addEventListener() method to add the mousemove event listener to the window object.

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 mousemove event returns a MouseEvent object on which we can access the clientX and clientY properties.

  • the clientX property returns the horizontal coordinate of the mouse within the application's viewport.

  • the clientY property returns the vertical coordinate of the mouse within the application's viewport.

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

The previous subheading shows how to get the global coordinates of the mouse.

As shown in the screenshot, the coordinates in the top left position of the viewport are (x 0, y 0) and the coordinates at the bottom right position of the viewport at (x MAX, y MAX).

react get mouse position

To get the mouse coordinates relative to an element on the page:

  1. Set the onMouseMove prop on an element or add an event listener on the window object.
  2. Subtract offsetLeft from clientX and offsetTop from clientY.
App.js
import {useEffect, useState} from 'react'; export default function App() { const [globalCoords, setGlobalCoords] = useState({x: 0, y: 0}); const [localCoords, setLocalCoords] = useState({x: 0, y: 0}); const handleMouseMove = event => { // 👇️ Get the mouse position relative to the element setLocalCoords({ x: event.clientX - event.target.offsetLeft, y: event.clientY - event.target.offsetTop, }); }; useEffect(() => { const handleGlobalMouseMove = event => { setGlobalCoords({ x: event.clientX, y: event.clientY, }); }; window.addEventListener('mousemove', handleGlobalMouseMove); return () => { window.removeEventListener( 'mousemove', handleGlobalMouseMove, ); }; }, []); return ( <div> <div onMouseMove={handleMouseMove} style={{ padding: '4rem', backgroundColor: 'lightgray', border: '1px solid black', width: '300px', }} > <h2> Relative: ({localCoords.x}, {localCoords.y}) </h2> </div> <br /> <h2> Global: ({globalCoords.x}, {globalCoords.y}) </h2> </div> ); }

get mouse position relative to element

The code for this article is available on GitHub

Subtracting offsetLeft from clientX returns the X coordinate of the mouse relative to the div element.

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

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

Subtracting offsetTop from clientY returns the Y coordinate of the mouse relative to the div element.

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 parent.

If you need to check if an element is in the viewport, click on the following article.

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.