File size: 986 Bytes
f5071ca |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import { useState, useCallback, RefObject } from 'react';
import * as ReactDOM from 'react-dom';
export const useAdjustedScroll = (ref: RefObject<HTMLElement>) => {
const [previousScroll, setPreviousScroll] = useState<{
top: number;
height: number;
}>();
/**
* Scrolls to the previous position or completely to bottom (on demand)
*/
const adjust = useCallback(
(scrollToBottom?: boolean) => {
if (!ref.current) return;
const node = ReactDOM.findDOMNode(ref.current) as HTMLElement;
const height =
!scrollToBottom && previousScroll
? previousScroll.height
: node.clientHeight;
node.scrollTop = node.scrollHeight - height;
// saves current scroll details
if (previousScroll && node.scrollTop !== previousScroll.top) {
setPreviousScroll({
top: node.scrollTop,
height: node.scrollHeight,
});
}
},
[ref, previousScroll]
);
return adjust;
};
|