2

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.)

Alexander Hemming
  • 753
  • 1
  • 6
  • 28

2 Answers2

2

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

Dhruv
  • 149
  • 4
  • That is the same as what I have written, but I used a functional component and the useRef hook. If it is different for functional components can you say what i have done wrong? – Alexander Hemming Jun 06 '20 at 08:48
0

pageYOffset is for the window.

such as window.pageYOFFset.

you need offsetTOp.

so

console.log(refTwo.current.offsetTop)

Alexander Hemming
  • 753
  • 1
  • 6
  • 28