how to restore page when going back in infinity scroll condition (react)

송지혁
3 min readApr 2, 2019

--

My service should restore page when user go back. Especially in searching page, when the user clicked the image, the page moves to post detail page

before click page (Page 1)
after click page (page2)

What i mean is that if user clicked back button in the page2, the user should see the before page. The scroll and posts should be in the same position

If this does not happen, user should find again from top. It is so uncomfortable. So i should make a code to solve this problem

componentWillUnmount(){

let previousInfo = {“scrollY”: window.scrollY , “coverurl”: this.state.coverurl, “page”: this.state.page, “totalPage”:this.state.totalPage }

let stringifiedInfo = JSON.stringify(previousInfo)

window.localStorage.setItem(“previousInfo”, stringifiedInfo);

}

First of all, i should save the information of before page. so i saved the information in the localstorage when the component unmount.

componentWillunmount will be activated after the component closed. The ScrollY means that where we are. the coverurl means that posts that already rendered in the page. it should be saved in localstorage

BECAUSE! i am using infinity scroll. if i want to let the scroll (0,1000), there should be posts in the page.But in infinity scroll, the posts rendering only when the user scrolls down. If the before page is 3, we cannot scroll the page to page 3! Because we do not have 3page when the page is loaded again. it started in page 1!

also the page and totalpage information is needed to restore page. so i put these information in the localstorage.

After user coming back to the page. we should rendering the posts and scroll down to the right Y position.

So i get the previous information from localstorage. Then make it state change by the information. I changed coverurl, page, scrollY, totalpage states.

After rendering before page’s coverurl, we also have to rendering the coverurl when the user scroll down. so i call a coverurl from server and add it in the coverurl state.

Finally we use window.scrollTo(0, this.state.scrollY) to go to the specific Y position. It should be used in ComponentDidmount. Because we make webpage scrolled after the posts rendered.

It was not easy to solve this problem. Because there is few information about this. I had to figure it out by myself how to do this. But after i solve this. I become so happy that i say thx to god that he let me become a programmer

--

--

No responses yet