File size: 910 Bytes
1e92f2d |
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 |
import { throttle } from 'lodash';
import { useEffect } from 'react';
const THROTTLE_DURATION = 400; // in ms
export default function useResize(
uplotRef: React.RefObject< uPlot >,
containerRef: React.RefObject< HTMLDivElement >
) {
useEffect( () => {
if ( ! uplotRef.current || ! containerRef.current ) {
return;
}
const resizeChart = throttle( () => {
// Repeat the check since resize can happen much later than event registration.
if ( ! uplotRef.current || ! containerRef.current ) {
return;
}
// Only update width, not height.
uplotRef.current.setSize( {
height: uplotRef.current.height,
width: containerRef.current.clientWidth,
} );
}, THROTTLE_DURATION );
resizeChart();
window.addEventListener( 'resize', resizeChart );
// Cleanup on unmount.
return () => window.removeEventListener( 'resize', resizeChart );
}, [ uplotRef, containerRef ] );
}
|