Created
September 8, 2016 16:06
-
-
Save DarrylD/d5654924703f3f3029b0c84779aafd30 to your computer and use it in GitHub Desktop.
A chat scroller for react
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' | |
/** | |
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