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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *