How can i get a ref to show me its pageYOffset?

Viewed 859

How do you retrieve pageYOffset from a ref? When I try this, it comes back undefined.

edit: (this is using the useRef hook and a functional component) codesandbox URL: https://codesandbox.io/s/prod-silence-8f07c?file=/src/App.js

//button to get offset
    <button style={{position:"fixed", top:"200px", right:"300px"}} 
    onClick={() =>{
      console.log(refTwo.current.pageYOffset)

    }}> test</button>

....

 <div ref={refTwo} className={two}> hello </div>

(Preferably not scrollY as I dont want to see how much has been scrolled, and page changes sometimes start people at halfway down the page.)

2 Answers

In the constructor define your ref as below. Also assign ref to div using this ref.

constructor(props) {
    super(props);
    this.refTwo = React.createRef();
}

<div ref={this.refTwo} />

Access using

this.refTwo.current.pageYOffset

Reference:https://reactjs.org/docs/refs-and-the-dom.html

pageYOffset is for the window.

such as window.pageYOFFset.

you need offsetTOp.

so

console.log(refTwo.current.offsetTop)

Related