Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Forked from swyxio/chatscroller.jsx
Created September 4, 2020 04:11
Show Gist options
  • Save wobsoriano/419e7ccd02b117ef9e604fa5f1a67dcb to your computer and use it in GitHub Desktop.
Save wobsoriano/419e7ccd02b117ef9e604fa5f1a67dcb 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