UNPKG

@base-ui-components/react

Version:

Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.

53 lines (52 loc) 1.46 kB
'use client'; import * as React from 'react'; import { useEnhancedEffect } from '../../utils/useEnhancedEffect.js'; import { useCompositeListContext } from './CompositeListContext.js'; /** * Used to register a list item and its index (DOM position) in the `CompositeList`. */ export function useCompositeListItem(params = {}) { const { label, metadata } = params; const { register, unregister, map, elementsRef, labelsRef } = useCompositeListContext(); const [index, setIndex] = React.useState(null); const componentRef = React.useRef(null); const ref = React.useCallback(node => { componentRef.current = node; if (index !== null) { elementsRef.current[index] = node; if (labelsRef) { const isLabelDefined = label !== undefined; labelsRef.current[index] = isLabelDefined ? label : node?.textContent ?? null; } } }, [index, elementsRef, labelsRef, label]); useEnhancedEffect(() => { const node = componentRef.current; if (node) { register(node, metadata); return () => { unregister(node); }; } return undefined; }, [register, unregister, metadata]); useEnhancedEffect(() => { const i = componentRef.current ? map.get(componentRef.current)?.index : null; if (i != null) { setIndex(i); } }, [map]); return React.useMemo(() => ({ ref, index: index == null ? -1 : index }), [index, ref]); }