Questions? Ask in Slack #vcc-ui
@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:
<View>/*index 0*/<AccordionComp>1</AccordionComp>/*index 1*/<AccordionComp>2</AccordionComp><Block>/*index 2*/<AccordionComp>3</AccordionComp></Block><Block><Block>/*index 3*/<AccordionComp>4</AccordionComp></Block></Block></View>
$ yarn add @volvo-cars/react-descendants
💡 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.
Example below shows how the component indices update with mounting and unmounting of components. Try clicking on each component.
It's also possible to nest providers however we like, each hook will update its corresponding context value without affecting other contexts.