Get scroll position with Reactjs

1634 views javascript

I use reactjs and want to handle scroll with click event.

Firstly, I rendered list of posts with componentDidMount.

Secondly, by click event on each post in list, It will display post detail and scroll to top (because I put post detail to top position of page).

Thirdly, by clicking "close button" in post detail, it will return previous list of posts but I want website will scroll to exactly to position of clicked post.

I use like this:

Click event to view post detail:

inSingle = (post, e) => {
        post: post,
        theposition: //How to get it here?
   window.scrollTo(0, 0);

I want to get state of theposition then I can do scroll exactly to position of clicked post by 'Close event'.

Thank you so much.

answered question

What version of react are you using?

@SungKim I am using the latest version

3 Answers


Like this?

theposition: e.y // or, e.pageY

posted this

You can add use event listener in react like you will use in other js framework or library.

componentDidMount() {
  window.addEventListener('scroll', this.listenToScroll)

componentWillUnmount() {
  window.removeEventListener('scroll', this.listenToScroll)

listenToScroll = () => {
  const winScroll =
    document.body.scrollTop || document.documentElement.scrollTop

  const height =
    document.documentElement.scrollHeight -

  const scrolled = winScroll / height

    theposition: scrolled,

posted this

Have an answer?


Please login first before posting an answer.