useAutoHeight
sora-ui/hooks-use-auto-heightFreeHook
A hook that allows you to automatically adjust the height of an element based on its content.
Install it
npx shadcn@latest add https://ui.soralabs.io.vn/r/hooks-use-auto-height.jsonSource
1"use client";23import * as React from "react";45interface AutoHeightOptions {6 includeParentBox?: boolean;7 includeSelfBox?: boolean;8}910export function useAutoHeight<T extends HTMLElement = HTMLDivElement>(11 deps: React.DependencyList = [],12 options: AutoHeightOptions = {13 includeParentBox: true,14 includeSelfBox: false,15 }16) {17 const ref = React.useRef<T | null>(null);18 const roRef = React.useRef<ResizeObserver | null>(null);19 const rafRef = React.useRef<number | null>(null);20 const [height, setHeight] = React.useState(0);2122 const scheduleHeight = React.useCallback((next: number) => {23 if (rafRef.current !== null) {24 cancelAnimationFrame(rafRef.current);25 }26 rafRef.current = requestAnimationFrame(() => {27 rafRef.current = null;28 setHeight(next);29 });30 }, []);3132 const measure = React.useCallback(() => {33 const el = ref.current;34 if (!el) {35 return 0;36 }3738 const base = el.getBoundingClientRect().height || 0;3940 let extra = 0;4142 if (options.includeParentBox && el.parentElement) {43 const cs = getComputedStyle(el.parentElement);44 const paddingY =45 (Number.parseFloat(cs.paddingTop || "0") || 0) +46 (Number.parseFloat(cs.paddingBottom || "0") || 0);47 const borderY =48 (Number.parseFloat(cs.borderTopWidth || "0") || 0) +49 (Number.parseFloat(cs.borderBottomWidth || "0") || 0);50 const isBorderBox = cs.boxSizing === "border-box";51 if (isBorderBox) {52 extra += paddingY + borderY;53 }54 }5556 if (options.includeSelfBox) {57 const cs = getComputedStyle(el);58 const paddingY =59 (Number.parseFloat(cs.paddingTop || "0") || 0) +60 (Number.parseFloat(cs.paddingBottom || "0") || 0);61 const borderY =62 (Number.parseFloat(cs.borderTopWidth || "0") || 0) +63 (Number.parseFloat(cs.borderBottomWidth || "0") || 0);64 const isBorderBox = cs.boxSizing === "border-box";65 if (isBorderBox) {66 extra += paddingY + borderY;67 }68 }6970 const dpr =71 typeof window === "undefined" ? 1 : window.devicePixelRatio || 1;72 const total = Math.ceil((base + extra) * dpr) / dpr;7374 return total;75 }, [options.includeParentBox, options.includeSelfBox]);7677 React.useLayoutEffect(() => {78 const el = ref.current;79 if (!el) {80 return;81 }8283 setHeight(measure());8485 if (roRef.current) {86 roRef.current.disconnect();87 roRef.current = null;88 }8990// … truncated
Files it writes
More from Sora UI
All 97 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| useControlledStatehooks-use-controlled-state | Sora UI | Hooks | Free | no deps | |
| useIsInViewhooks-use-is-in-view | Sora UI | Hooks | Free | 1 dep | |
| usePrefersReducedMotionhooks-use-prefers-reduced-motion | Sora UI | Hooks | Free | no deps |
