import React, { useEffect, useRef, useState } from 'react'; export function TableFloatingScroll(props) { const ref = useRef(null); const contentRef = useRef(null); const scrollBlockRef = useRef(null); const [width, setWidth] = useState(0); const [containerWidth, setContainerWidth] = useState(0); const [position, setPosition] = useState<'relative' | 'fixed'>('relative'); useEffect(() => { const scrollBlockRefInstance = scrollBlockRef.current; contentRef.current = ref.current?.firstChild as HTMLElement; // @ts-ignore setContainerWidth(ref.current.offsetWidth); setWidth(contentRef.current.scrollWidth); const elementOffset = contentRef.current.offsetTop + contentRef.current.offsetHeight; function onBodyScroll() { const currentScroll = window.pageYOffset + window.innerHeight; if ( currentScroll < elementOffset && // @ts-ignore currentScroll > contentRef.current.offsetTop ) { setPosition('fixed'); } else if ( currentScroll >= elementOffset || // @ts-ignore currentScroll <= contentRef.current.offsetTop ) { setPosition('relative'); } } function onBlockScroll() { // @ts-ignore ref.current.scrollLeft = scrollBlockRefInstance.scrollLeft; } // @ts-ignore scrollBlockRefInstance.addEventListener('scroll', onBlockScroll); document.addEventListener('scroll', onBodyScroll); window.addEventListener('resize', () => { if (ref.current?.offsetWidth) { // @ts-ignore setContainerWidth(ref.current.offsetWidth); } if (contentRef.current?.offsetWidth) { // @ts-ignore setWidth(contentRef.current.scrollWidth); } }); return () => { // @ts-ignore scrollBlockRefInstance.removeEventListener('scroll', onBlockScroll); document.removeEventListener('scroll', onBodyScroll); }; }, []); return ( <>
{props.children}
); } export default TableFloatingScroll;