Skip to content

Instantly share code, notes, and snippets.

@haldarmahesh
Created October 19, 2018 12:20
Show Gist options
  • Select an option

  • Save haldarmahesh/385f38cc9b3ee2b8e9f319cb033687b6 to your computer and use it in GitHub Desktop.

Select an option

Save haldarmahesh/385f38cc9b3ee2b8e9f319cb033687b6 to your computer and use it in GitHub Desktop.
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