Skip to content

Instantly share code, notes, and snippets.

@swyxio
Last active November 15, 2020 21:55
Show Gist options
  • Save swyxio/e12678b100478dad7f6d94efb46644e4 to your computer and use it in GitHub Desktop.
Save swyxio/e12678b100478dad7f6d94efb46644e4 to your computer and use it in GitHub Desktop.
Handy Scroll window manager component for building a Slack-like Chat experience - when you want your chat window to autoscroll down when new messages appear, BUT not while you're scrolling up. Also useful for feedlike or log display components. from ryan florence workshop chat example (course at https://courses.reacttraining.com/courses/517181/…
function ChatScroller(props) {
const ref = useRef()
const shouldScrollRef = useRef(true)
useEffect(()=> {
if (shouldScrollRef.current) {
const node = ref.current
node.scrollTop = node.scrollheight
}
})
const handleScroll = () => {
const node = ref.current
const { scrollTop, clientHeight, scrollHeight } = node
const atBottom = scrollHeight === clientHeight + scrollTop
shouldScrollRef.current = atBottom
}
return <div {...props} ref={ref} onScroll={handleScroll} />
}
// usage
function ChatWindow(messages) {
return <ChatScroller>
{messages.map(/* display all the messages */)}
</ChatScroller>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment