Last active
June 27, 2021 22:24
-
-
Save Izhaki/ea32f4d3813a27bd4e9d137aff7a71c1 to your computer and use it in GitHub Desktop.
React useAutoScrollToBottom.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
export default function useAutoScrollToBottom(deps) { | |
const paused = React.useRef(false); | |
const element = React.useRef<HTMLDivElement | null>(null); | |
const onWheel = React.useCallback(() => { | |
const { scrollTop, scrollHeight, offsetHeight } = element.current || { | |
scrollTop: 0, | |
scrollHeight: 0, | |
offsetHeight: 0, | |
}; | |
paused.current = scrollHeight - (scrollTop + offsetHeight) > 4; | |
}, []); | |
const ref = React.useCallback( | |
(el) => { | |
if (el) { | |
element.current = el; | |
el.addEventListener('wheel', onWheel, { passive: true }); | |
} else if (element.current !== null) { | |
element.current.removeEventListener('wheel', onWheel); | |
element.current = null; | |
} | |
}, | |
[onWheel] | |
); | |
React.useLayoutEffect(() => { | |
if (element.current && !paused.current) { | |
element.current.scrollTop = element.current.scrollHeight; | |
} | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, deps); | |
return { ref }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment