Use Tab Observer
blode-ui/use-tab-observerFreeUtility
A hook that observes and tracks the active tab indicator position.
Install it
npx shadcn@latest add https://raw.githubusercontent.com/mblode/blode-ui/main/public/r/use-tab-observer.jsonSource
1import React from "react";23interface TabObserverOptions {4 onActiveTabChange?: (index: number, element: HTMLElement) => void;5}67export const useTabObserver = ({ onActiveTabChange }: TabObserverOptions = {}) => {8 const listRef = React.useRef<HTMLDivElement>(null);9 const onActiveTabChangeRef = React.useRef(onActiveTabChange);1011 React.useEffect(() => {12 onActiveTabChangeRef.current = onActiveTabChange;13 }, [onActiveTabChange]);1415 const handleUpdate = React.useCallback(() => {16 if (listRef.current) {17 const tabs = listRef.current.querySelectorAll('[role="tab"]');18 for (let i = 0; i < tabs.length; i += 1) {19 const el = tabs[i];20 if (!(el instanceof HTMLElement)) {21 continue;22 }23 const isActive =24 Object.hasOwn(el.dataset, "active") ||25 el.dataset.state === "active" ||26 el.getAttribute("aria-selected") === "true";2728 if (isActive) {29 onActiveTabChangeRef.current?.(i, el);30 break;31 }32 }33 }34 }, []);3536 React.useEffect(() => {37 const resizeObserver = new ResizeObserver(handleUpdate);38 const mutationObserver = new MutationObserver(handleUpdate);3940 if (listRef.current) {41 resizeObserver.observe(listRef.current);42 mutationObserver.observe(listRef.current, {43 attributes: true,44 childList: true,45 subtree: true,46 });47 }4849 const handleWindowUpdate = () => {50 handleUpdate();51 };5253 window.addEventListener("resize", handleWindowUpdate);54 window.addEventListener("orientationchange", handleWindowUpdate);55 document.fonts?.addEventListener?.("loadingdone", handleWindowUpdate);5657 handleUpdate();5859 return () => {60 resizeObserver.disconnect();61 mutationObserver.disconnect();62 window.removeEventListener("resize", handleWindowUpdate);63 window.removeEventListener("orientationchange", handleWindowUpdate);64 document.fonts?.removeEventListener?.("loadingdone", handleWindowUpdate);65 };66 }, [handleUpdate]);6768 return { listRef };69};
Files it writes
More from blode/ui
All 85 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| Use Copy To Clipboarduse-copy-to-clipboard | blode/ui | Utilities | Free | no deps | |
| Use Mobileuse-mobile | blode/ui | Utilities | Free | no deps | |
| Utilsutils | blode/ui | Utilities | Free | 2 deps |
