Categories
React Answers

How to get a div’s offsetTop positions in React?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.