Sometimes, we want to get a div’s offsetTop positions in React.
In this article, we’ll look at how to get a div’s offsetTop positions in React.
How to get a div’s offsetTop positions in React?
To get a div’s offsetTop positions in React, we can get it from the ref assigned to the element.
For instance, we write
import { useRef } from "react";
function Component() {
const inputRef = useRef();
return (
<>
<input ref={inputRef} />
<div
onScroll={() => {
const { offsetTop } = inputRef.current;
//...
}}
>
...
</div>
</>
);
}
to assign the inputRef
to the input.
Then we get the offsetTop
property from the inputRef.current
property which has the input element.
Conclusion
To get a div’s offsetTop positions in React, we can get it from the ref assigned to the element.