Home > Enterprise >  React Router v6 - preserve scroll position
React Router v6 - preserve scroll position

Time:03-01

I have a homepage where user's feed is shown. When user clicks on one of the feed card it goes to a different url, when user comes back to the homepage, it scrolls to top. I want to preserve the scroll position of the homepage so user can continue scrolling from previous scroll position.

I tried to use this method https://stackoverflow.com/a/67124040/14786214 but it does not work on Router v6

CodePudding user response:

Create a component to manage the feed's state, e.g. stateSaver.js:

const state = {}

export const saveState = (component, object) => {
    
    state[component] = object
    
}

export const getState = (component) => {
    
    return state[component]
    
}

Then, within your feed.js, retreive the scroll position and use a listener to update it:

import { getState, saveState } from './stateSaver';

useEffect(() => {
        
    if(getState('Feed')){
     
        let { scrollY } = getState('Feed')
        
        window.scrollTo(0, scrollY), 200)
        
    }
    
}, [])


useEffect(() => {
    
    const save = () => {
        
        saveState('Feed', {  scrollY: window.pageYOffset  })        
        
    }
    
    save()
    
    document.addEventListener('scroll', save)
    
    return () => document.removeEventListener('scroll', save)
    
}, [])

The solution works assuming that you are working with a single web application.

  • Related