Skip to content

Instantly share code, notes, and snippets.

@DarrylD
Created September 8, 2016 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarrylD/d5654924703f3f3029b0c84779aafd30 to your computer and use it in GitHub Desktop.
Save DarrylD/d5654924703f3f3029b0c84779aafd30 to your computer and use it in GitHub Desktop.
A chat scroller for react
import React from 'react'
/**
example:
<ChatScroller ref="chatScroller">
{this.renderStuff()}
</ChatScroller>
to force move the containt to the bottom:
...
handleSomeEvent(){
this.refs.chatScroller.moveToBottom()
}
..
*/
export default class ChatScroller extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
// settign this to true so when we mount, we can move directly to bottom
this.pinToBottom = true
}
componentDidUpdate() {
//since it updates on mout, it will go directly to the bottom
if (this.pinToBottom) this.scrollToBottom()
}
scrollToBottom() {
const node = this.refs.container
if (node) node.scrollTop = node.scrollHeight
}
handleScroll(event) {
const { clientHeight, scrollTop, scrollHeight } = event.target
this.pinToBottom = clientHeight + scrollTop > (scrollHeight - 10)
}
moveToBottom(context){
if (context) {
debugger
return context.refs.chatScroller.moveToBottom()
}
this.pinToBottom = true
}
render(){
const {children, ...rest} = this.props
return(
<div {...rest} ref="container" onScroll={::this.handleScroll}>
{children}
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment