Hooks
useAutoHeight
Hook that tracks element height changes via ResizeObserver for smooth animated transitions.
useAutoHeight
A hook that uses ResizeObserver to track an element's content height, enabling smooth animated height transitions when content changes dynamically.
Import
import { useAutoHeight } from '@mks2508/mks-ui/react';Basic Usage
function ExpandableContent() {
const [expanded, setExpanded] = useState(false);
const { ref, height } = useAutoHeight();
return (
<div
style={{ height, overflow: 'hidden', transition: 'height 0.3s ease' }}
>
<div ref={ref}>
<p>Always visible content</p>
{expanded && <p>Additional content that changes height</p>}
</div>
</div>
<Button onClick={() => setExpanded(!expanded)}>Toggle</Button>
);
}How It Works
- Attach the returned
refto the element whose height you want to track - The hook uses
ResizeObserverto monitor size changes - The
heightvalue updates whenever the element resizes - Apply
heightto a wrapper element with CSS transitions for smooth animation
API Reference
Parameters
None.
Return Value
| Property | Type | Description |
|---|---|---|
ref | RefCallback<HTMLElement> | Attach to the content element |
height | number | 'auto' | Current measured height in pixels |