Transitions
Auto height
Expands to the content's real height and keeps tracking it with a ResizeObserver — no max-height guessing, no clipping.
- accordion
- disclosure
- resize-observer
Preview
Height is not animatable from auto, so the usual workaround is a max-height guess that either clips long content or lands with a lag on short content.
Measuring the child and animating to a concrete pixel height fixes both — and a ResizeObserver keeps it correct when the content changes while open.
Usage
<AutoHeight open={isOpen}>
<Details {...record} />
</AutoHeight>54 lines
"use client";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/cn";
export interface AutoHeightProps {
open?: boolean;
duration?: number;
/** Fade the contents alongside the height change. */
fade?: boolean;
children: React.ReactNode;
className?: string;
}
/**
* Animates between 0 and the content's natural height — including when the
* content itself resizes while open, which a plain CSS transition can't do.
*/
export function AutoHeight({
open = true,
duration = 300,
fade = true,
children,
className,
}: AutoHeightProps) {
const inner = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(0);
useEffect(() => {
const el = inner.current;
if (!el) return;
const measure = () => setHeight(el.offsetHeight);
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
return () => ro.disconnect();
}, [children]);
return (
<div
className={cn("overflow-hidden", className)}
style={{
height: open ? height : 0,
opacity: fade ? (open ? 1 : 0) : 1,
transition: `height ${duration}ms var(--ease-out-quint), opacity ${duration * 0.7}ms linear`,
}}
aria-hidden={!open}
>
<div ref={inner}>{children}</div>
</div>
);
}
export default AutoHeight;