File size: 1,280 Bytes
75fefa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"use client";

import { motion, MotionProps, TargetAndTransition } from "motion/react";
import { useEffect, useRef, useState } from "react";

import { cn } from "@/utils/cn";

type AnimatedHeight = {
  children: React.ReactNode;
  animate?: TargetAndTransition;
  initial?: TargetAndTransition;
  exit?: TargetAndTransition;
  className?: string;
  transition?: MotionProps["transition"];
};

export default function AnimatedHeight({ children, ...attrs }: AnimatedHeight) {
  const containerRef = useRef<HTMLDivElement>(null);

  const [height, setHeight] = useState<number | "auto">("auto");

  useEffect(() => {
    const child = containerRef.current?.children[0] as Element;

    const updateHeight = () => {
      if (!child) return;

      setHeight(child.clientHeight);
    };

    updateHeight();

    const resizeObserver = new ResizeObserver(updateHeight);

    resizeObserver.observe(child);

    return () => resizeObserver.disconnect();
  }, []);

  return (
    <motion.div
      {...attrs}
      animate={{
        height,
        ...attrs.animate,
      }}
      className={cn(attrs.className)}
      initial={{
        height,
        ...attrs.initial,
      }}
      ref={containerRef}
    >
      <div className="h-max">{children}</div>
    </motion.div>
  );
}