I have a method like that to add shadow to parent container edges to indicate that there is a content to scroll.
export function useScrollWithShadow(
dir: 'horizontal' | 'vertical',
) {
const [scrollTop, setScrollTop] = useState(0);
const [scrollLeft, setScrollLeft] = useState(0);
const [scrollHeight, setScrollHeight] = useState(0);
const [scrollWidth, setScrollWidth] = useState(0);
const [clientHeight, setClientHeight] = useState(0);
const [clientWidth, setClientWidth] = useState(0);
const margin = 4;
const onScrollHandler = (event: any) => {
setScrollTop(event.target.scrollTop);
setScrollLeft(event.target.scrollLeft);
setScrollHeight(event.target.scrollHeight);
setScrollWidth(event.target.scrollWidth);
setClientHeight(event.target.clientHeight);
setClientWidth(event.target.clientWidth);
};
useEffect(() => {}, []);
function getBoxShadow() {
const isBottom = clientHeight === scrollHeight - scrollTop;
const isTop = scrollTop === 0;
const isBetween = scrollTop > 0 && clientHeight < scrollHeight - scrollTop;
const isRight = scrollWidth - clientWidth - scrollLeft <= margin;
const isLeft = scrollLeft <= margin;
const isBetweenHorizontally = !isLeft && !isRight;
let boxShadow = 'none';
const top = 'inset 0 8px 5px -5px var(--slate-10)';
const bottom = 'inset 0 -8px 5px -5px var(--slate-10)';
const left = 'var(--slate-10) 20px 0px 10px -10px inset';
const right = 'var(--slate-10) -20px 0px 10px -10px inset';
if (dir === 'vertical') {
if (isTop) {
boxShadow = bottom;
} else if (isBetween) {
boxShadow = `${top}, ${bottom}`;
} else if (isBottom) {
boxShadow = top;
}
return boxShadow;
} else {
if (scrollWidth > clientWidth) {
if (isLeft) {
boxShadow = right;
} else if (isBetweenHorizontally) {
boxShadow = `${left}, ${right}`;
} else if (isRight) {
boxShadow = left;
}
}
return boxShadow;
}
}
return { boxShadow: getBoxShadow(), onScrollHandler };
}
Unfortunately, it does not work on mount and to show shadow, I need to scroll which is not a good user expercience because I want to let user now that there is a content to scroll before scrolling. Any ideas how to imrove the code?