In today’s blog post, we will discuss how to get the X and Y position of an element in React JS. Getting the position of an element can be very useful in various situations, such as triggering certain events based on the user’s interaction with the target element.
In React JS, getting the position of an element can be achieved through various methods. But in this tutorial, we will use the offsetLeft and offsetTop properties to get the position of the element.
As you can see in the above demo video, we have rendered some text and a card in between the text. The card displays the X and Y position of its top-left corner. The X and Y position of the card is updated whenever the window is resized.
How to get the position of an element in React JS
To begin with, let’s first create a React JS project using create-react-app.
npx create-react-app get-element-position
After creating our React JS project, let’s write the code to get the X and Y position of an element inside the App.js file.
App.js
import React, { useEffect, useRef, useState } from "react";
function App() {
const elementRef = useRef(null);
const [position, setPosition] = useState({ x: 0, y: 0 });
useEffect(() => {
function handleResize() {
const x = elementRef.current.offsetLeft;
const y = elementRef.current.offsetTop;
setPosition({ x, y });
}
handleResize(); // initial call to get position of the element on mount
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, [elementRef]);
return (
<div>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Labore placeat
quam dolorem ab, iure nam nesciunt, facere sed nihil molestias
consectetur reprehenderit cupiditate itaque pariatur quia tenetur omnis
nisi numquam quibusdam reiciendis beatae laboriosam earum.
</p>
<div className="card" ref={elementRef}>
<h3>Position</h3>
<p>
X: <strong>{position.x}</strong>
</p>
<p>
Y: <strong>{position.y}</strong>
</p>
</div>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Labore placeat
quam dolorem ab, iure nam nesciunt, facere sed nihil molestias
consectetur reprehenderit cupiditate itaque pariatur quia tenetur omnis
nisi numquam quibusdam reiciendis beatae laboriosam earum.
</p>
</div>
);
}
export default App;
In the above code, we have created a new reference `elementRef`
using the useRef hook and initialized it to null. This reference will be attached to the element in JSX to get the position.
Then we have a useState variable `position`
. The value of `position`
is set to an object with two properties x and y, both initialized to 0.
Inside the useEffect hook, we have written an event listener for the “resize” event and a function `handleResize()`
to handle the event. This function gets the current position of the card element and updates the `position`
state variable using setPosition.
Finally, our JSX code consists of paragraphs of text and a card element. The card element has a ref attribute that is set to the `elementRef`
reference created earlier. Inside the card element, we are displaying the X and Y position values.
Also check out:
Conclusion
In conclusion, we have learned how to use the useRef and useState hooks to get the position of an element on the screen and dynamically update it on window resize. Hope this was useful.