Skip to content

Instantly share code, notes, and snippets.

@jeffijoe
Last active November 1, 2023 18:51
Show Gist options
  • Save jeffijoe/510f6823ef809e3711ed307823b48c0a to your computer and use it in GitHub Desktop.
Save jeffijoe/510f6823ef809e3711ed307823b48c0a to your computer and use it in GitHub Desktop.
Save and restore scroll position in React
// This example will manage the scroll position for a DOM element.
// The key must be unique per managed element, as it is used as a key in a store
// when saving and restoring the position.
import React from 'react'
import ScrollManager from './ScrollManager'
export default function App() {
return (
<div>
<ScrollManager scrollKey="some-list-key">
{({ connectScrollTarget, ...props }) =>
<div ref={connectScrollTarget} style={{ overflow: 'auto', maxHeight: 500 }}>
If this div is unmounted and remounted, scroll position is restored.
</div>
}
</ScrollManager>
</div>
)
}
// This example will manage the scroll position for the window.
// The key must be unique per screen, as it is used as a key in a store
// when saving and restoring the position.
import React from 'react'
import ScrollManager from './ScrollManager'
export default function App() {
return (
<div>
<ScrollManager scrollKey="some-screen-key" />
<div>
Here be content. If this component is unmounted and remounted, scrolling position will be restored.
</div>
</div>
)
}
/*
The MIT License
Copyright (c) Jeff Hansen 2018 to present.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from 'react'
import requestAnimationFrame from 'raf'
export const memoryStore = {
_data: new Map(),
get(key) {
if (!key) {
return null
}
return this._data.get(key) || null
},
set(key, data) {
if (!key) {
return
}
return this._data.set(key, data)
}
}
/**
* Component that will save and restore Window scroll position.
*/
export default class ScrollPositionManager extends React.Component {
constructor(props) {
super(...arguments)
this.connectScrollTarget = this.connectScrollTarget.bind(this)
this._target = window
}
connectScrollTarget(node) {
this._target = node
}
restoreScrollPosition(pos) {
pos = pos || this.props.scrollStore.get(this.props.scrollKey)
if (this._target && pos) {
requestAnimationFrame(() => {
scroll(this._target, pos.x, pos.y)
})
}
}
saveScrollPosition(key) {
if (this._target) {
const pos = getScrollPosition(this._target)
key = key || this.props.scrollKey
this.props.scrollStore.set(key, pos)
}
}
componentDidMount() {
this.restoreScrollPosition()
}
componentWillReceiveProps(nextProps) {
if (this.props.scrollKey !== nextProps.scrollKey) {
this.saveScrollPosition()
}
}
componentDidUpdate(prevProps) {
if (this.props.scrollKey !== prevProps.scrollKey) {
this.restoreScrollPosition()
}
}
componentWillUnmount() {
this.saveScrollPosition()
}
render() {
const { children = null, ...props } = this.props
return (
children &&
children({ ...props, connectScrollTarget: this.connectScrollTarget })
)
}
}
ScrollPositionManager.defaultProps = {
scrollStore: memoryStore
}
function scroll(target, x, y) {
if (target instanceof window.Window) {
target.scrollTo(x, y)
} else {
target.scrollLeft = x
target.scrollTop = y
}
}
function getScrollPosition(target) {
if (target instanceof window.Window) {
return { x: target.scrollX, y: target.scrollY }
}
return { x: target.scrollLeft, y: target.scrollTop }
}
@MandyMeindersma
Copy link

Question for you! I am in the midst of implementing this for a project and i am running into some weird behaviour (I swear I implemented it right but it doesn't seem to be remembering scroll). I am wondering if it has anything to do with componentWillReceiveProps() being a legacy method?

@jeffijoe
Copy link
Author

@dvornikov I think without it, it wouldn't restore it correctly, but I don't remember anymore.

@MandyMeindersma That's possible, did you try prefixing it as per the React 16+ docs? I haven't been working on the project where I used this for a while.

@MandyMeindersma
Copy link

@jeffijoe I think you are right.

I didn't spend more time on this (ex prefixing the docs) since my team has decided to forget about scrolling for now. So I don't really have helpful information for you :P Sorry

@samuelkarani
Copy link

@ugokoli
Copy link

ugokoli commented Sep 5, 2020

Thanks you very much. It was helpful for me.

Though i'm very interesting why do you call the scroll method using requestAnimationFrame? There's no repeating actions.

requestAnimationFrame is required for rendering a new scroll position at the appropriate time. Good thing is that the window object has it. No need installing raf ie use window.requestAnimationFrame(callback)

Another update is that instead of using componentWillReceiveProps()
use;

    shouldComponentUpdate(nextProps, nextState, nextContext) {
        if (this.props.scrollKey !== nextProps.scrollKey) {
            this.saveScrollPosition()
        }
        return true;
    }

I must commend @jeffijoe for this sleek solution!

@henry-luo
Copy link

Thanks for the handy script. It works great!

@rajanlagah
Copy link

I searched and got your soln and it is too big. So I thought a bit and implemented this by.

  • Click the button to load more list items
  • After loading grab the element previously at the end of the list
  • and then use js function scrollIntoView() to the grabbed element.

That is working fine for me is this code doing something more?
Am I missing something?

@jeffijoe
Copy link
Author

I searched and got your soln and it is too big. So I thought a bit and implemented this by.

  • Click the button to load more list items
  • After loading grab the element previously at the end of the list
  • and then use js function scrollIntoView() to the grabbed element.

That is working fine for me is this code doing something more?
Am I missing something?

Mine restores the exact position that was saved.

@BenMansley
Copy link

BenMansley commented Oct 19, 2021

This was excellent, thank you! I created a simple version for a single component using React hooks, working as follows. Currently just storing y position, but scrollLeft would be trivial to add.

const memoryStore = new Map();

const component = ({..., scrollStore: memoryStore}) => {
  
  const containerEl = useRef(null);  

  useEffect(() => {
    const scrollTop = scrollStore.get('scrollTop');

    if ((scrollTop || scrollTop === 0) && containerEl.current) {
      containerEl.current.scrollTop = scrollTop;
    }

    return () => {
      const currentScrollTop = containerEl.current.scrollTop;
      if (currentScrollTop || currentScrollTop === 0) {
        scrollStore.set('scrollTop', currentScrollTop);
      }
    };
  }, []);

 // component logic
}

@agnel
Copy link

agnel commented Mar 4, 2022

This was excellent, thank you! I created a simple version for a single component using React hooks, working as follows. Currently just storing y position, but scrollLeft would be trivial to add.

const memoryStore = new Map();

const component = ({..., scrollStore: memoryStore}) => {
  
  const containerEl = useRef(null);  

  useEffect(() => {
    const scrollTop = scrollStore.get('scrollTop');

    if ((scrollTop || scrollTop === 0) && containerEl.current) {
      containerEl.current.scrollTop = scrollTop;
    }

    return () => {
      const currentScrollTop = containerEl.current.scrollTop;
      if (currentScrollTop || currentScrollTop === 0) {
        scrollStore.set('scrollTop', currentScrollTop);
      }
    };
  }, []);

 // component logic
}

I made use of localStorage for storing the scrollTop value. By doing this, the scroll position is restored even if the browser window/tab was reopened after closing it.

@ServOKio
Copy link

ServOKio commented Mar 19, 2022

This was excellent, thank you! I created a simple version for a single component using React hooks, working as follows. Currently just storing y position, but scrollLeft would be trivial to add.

const memoryStore = new Map();

const component = ({..., scrollStore: memoryStore}) => {
  
  const containerEl = useRef(null);  

  useEffect(() => {
    const scrollTop = scrollStore.get('scrollTop');

    if ((scrollTop || scrollTop === 0) && containerEl.current) {
      containerEl.current.scrollTop = scrollTop;
    }

    return () => {
      const currentScrollTop = containerEl.current.scrollTop;
      if (currentScrollTop || currentScrollTop === 0) {
        scrollStore.set('scrollTop', currentScrollTop);
      }
    };
  }, []);

 // component logic
}

@BenMansley okay, I did something like this:

useEffect(() => {
    if (props.setChatScroll && props.channel.scroll_pos !== -1) {
        requestAnimationFrame(() => {
            props.setChatScroll.current.scrollTop = props.channel.scroll_pos;
        });
    }
    return () => {
        const currentScrollTop = props.setChatScroll.current.scrollTop;
        if (props.setChatScroll.current && props.setChatScroll.current) props.guildManager.updateScrollPosition(props.guild.id, props.channel.id, currentScrollTop);
    }
}, [props.channel.id]);

scroll_pos - saved value
props.setChatScroll - scrollable ref

Scrollbar is at the bottom, okay

But when I change the channel - I get 0 from props.setChatScroll.current.scrollTop

2022-03-19_04-34_1
Why ?

or with onScroll={()=> console.log(props.setChatScroll.current.scrollTop)} on scrollable block

What's happening?

Looks like props.setChatScroll.current.scrollTop is updated faster than useEffect processes the position value

2022-03-19_05-24

Should we use multiple refs per channel or store a onScroll value somewhere?

I use this:

useEffect(() => {
    if (props.setChatScroll && props.channel.scroll_pos !== -1) {
        requestAnimationFrame(() => {
            props.setChatScroll.current.scrollTop = props.channel.scroll_pos;
        })
    }
    return () => {
        //this updates the value of props.channel.scroll_pos (-1 - default value (null))
        if (props.channel.temp_pos !== -1) props.guildManager.updateScrollPosition(props.guild.id, props.channel.id, props.channel.temp_pos);
    }
}, [props.channel.id]);

and

//this updates the value of props.channel.temp_pos (-1 - default value (null))
onScroll={() => props.guildManager.updateStoreScroll(props.guild.id, props.channel.id, props.setChatScroll.current.scrollTop)}

on scrollable and it works ✨

@Priyanka-spak
Copy link

Thank you, it helped me alot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment