@volvo-cars/react-descendants
A React hook that helps keep track of the indices of descendant components. It's useful for places where the exact rendering order of a descendent component is unknown. It allows each descendant component to know its index relative other components or renders of this specific component.
This way we can use component composition any way we like while knowing the exact index of each component:
💡 This package includes Typescript definitions
We first need to wrap the components which we want to know the rendering index for with a DescendantsIndexProvider
and consume the index
with useDescendantIndex
. The hook will return a ref
that needs to be passed to the react element to keep track off.
Index:
Index:
Index:
Example below shows how the component indices update with mounting and unmounting of components. Try clicking on each component.
Component 1 | index:
Component 2 | index:
Component 3 | index:
Component 4 | index:
Component 5 | index:
It's also possible to nest providers however we like, each hook will update its corresponding context value without affecting other contexts.
Component 1 | index:
Component 2 | index:
Component 3 | index:
Accordion 1 | index:
Accordion 2 | index:
Component 4 | index:
Component 5 | index: