@volvo-cars/react-descendants
v0.6.0
Published
A React hook that helps keep track of the indices of descendant components
Downloads
385
Keywords
Readme
@volvo-cars/react-descendants
A React utility for tracking the indices of descendant components, regardless of how deeply they are nested in the component tree. Useful for building accessible composite components (e.g. accordions, tabs, carousels) where the rendering order of children isn't known ahead of time.
What's included
createDescendantsIndexContext— Creates a context and hook pair (DescendantsIndexProvider+useDescendantIndex) that automatically assigns a stable index to each registered descendant, updating correctly as components mount and unmount
React 18.2 or 19 is required.
Installation
yarn add @volvo-cars/react-descendantsExample
const { DescendantsIndexProvider, useDescendantIndex } =
createDescendantsIndexContext();
function Item() {
const { ref, index } = useDescendantIndex();
return <div ref={ref}>Item {index}</div>;
}
function List() {
return (
<DescendantsIndexProvider>
<Item />
<Item />
<Item />
</DescendantsIndexProvider>
);
}