@equinor/eds-utils
Version:
Utility functions and hooks for the Equinor Design System
35 lines (32 loc) • 948 B
JavaScript
import { useEffect } from 'react';
const useAutoResize = (targetEl, maxHeight) => {
useEffect(() => {
const handleResize = () => {
targetEl.style.height = 'auto';
const {
scrollHeight,
clientHeight
} = targetEl;
let newHeight = clientHeight;
if (maxHeight > newHeight) {
newHeight = Math.min(maxHeight, Math.max(scrollHeight, newHeight));
if (scrollHeight > maxHeight) {
targetEl.style.overflow = 'auto';
} else {
targetEl.style.overflow = 'hidden';
}
if (newHeight > clientHeight) {
targetEl.style.height = `${newHeight}px`;
}
}
};
if (targetEl && maxHeight) {
handleResize();
targetEl.addEventListener('keyup', handleResize, true);
}
return () => {
targetEl?.removeEventListener('keyup', handleResize, true);
};
}, [targetEl, maxHeight]);
};
export { useAutoResize };