Created
October 19, 2018 12:20
-
-
Save haldarmahesh/385f38cc9b3ee2b8e9f319cb033687b6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| type Snapshot = number | null; | |
| class ScrollingList extends React.Component<Props, State, Snapshot> { | |
| listRef = React.createRef(); | |
| getSnapshotBeforeUpdate( | |
| prevProps: Props, | |
| prevState: State | |
| ): Snapshot { | |
| // Are we adding new items to the list? | |
| // Capture the current height of the list so we can adjust scroll later. | |
| if (prevProps.list.length < this.props.list.length) { | |
| return this.listRef.value.scrollHeight; | |
| } | |
| return null; | |
| } | |
| componentDidUpdate( | |
| prevProps: Props, | |
| prevState: State, | |
| snapshot: Snapshot | |
| ) { | |
| // If we have a snapshot value, then we've just added new items. | |
| // Adjust scroll so these new items don't push the old ones out of view. | |
| if (snapshot !== null) { | |
| this.listRef.value.scrollTop += | |
| this.listRef.value.scrollHeight - snapshot; | |
| } | |
| } | |
| render() { | |
| return ( | |
| <div ref={this.listRef}>{/* ...contents... */}</div> | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment