Skip to content

useDynamicRefs

function useDynamicRefs<T>(options?): DynamicRefGetter<T>;

Defined in: use-dynamic-refs.ts:78

React hook that returns a ref “getter” function. Call the getter with a string key to get (or create) a RefObject for that key. Useful for dynamic lists, tabs, or any UI where the number of refs isn’t known at compile time.

Type Parameter Description
T The element type for the refs (e.g. HTMLDivElement)
Parameter Type Description
options? UseDynamicRefsOptions Optional configuration

DynamicRefGetter<T>

A DynamicRefGetter function

import { useDynamicRefs } from "@xtandard/lib/react";
function TabList({ tabs }: { tabs: string[] }) {
const getRef = useDynamicRefs<HTMLButtonElement>();
return (
<div>
{tabs.map((tab) => (
<button key={tab} ref={getRef(tab)}>
{tab}
</button>
))}
</div>
);
}
// Scroll to a specific item
const getRef = useDynamicRefs<HTMLDivElement>();
function scrollTo(id: string) {
getRef(id)?.current?.scrollIntoView({ behavior: "smooth" });
}