Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.