Skip to content

Instantly share code, notes, and snippets.

@Izhaki
Last active June 27, 2021 22:24
Show Gist options
  • Select an option

  • Save Izhaki/ea32f4d3813a27bd4e9d137aff7a71c1 to your computer and use it in GitHub Desktop.

Select an option

Save Izhaki/ea32f4d3813a27bd4e9d137aff7a71c1 to your computer and use it in GitHub Desktop.
React useAutoScrollToBottom.ts
import React from 'react';
export default function useAutoScrollToBottom(deps) {
const pause = React.useRef(false);
const element = React.useRef<HTMLDivElement | null>(null);
const ref = React.useCallback((el) => {
function onWheel() {
const { scrollTop, scrollHeight, offsetHeight } = element.current || {
scrollTop: 0,
scrollHeight: 0,
offsetHeight: 0,
};
pause.current = scrollHeight - (scrollTop + offsetHeight) > 4;
}
if (el) {
element.current = el;
el.addEventListener('wheel', onWheel, { passive: true });
} else if (element.current !== null) {
element.current.removeEventListener('wheel', onWheel);
element.current = null;
}
}, []);
React.useLayoutEffect(() => {
if (element.current && !pause.current) {
element.current.scrollTop = element.current.scrollHeight;
}
}, deps);
return { ref };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment