I’m looking for a way to get access to position of each child component within it’s parent
I have a component called Slider
which can have multiple child components. lets call them SliderSection
and each SliderSection
can have multiple SliderStep
components.
It looks something like this:
<Slider>
<SliderSection>
<SliderStep>step 1</SliderStep>
<SliderStep>step 2</SliderStep>
<SliderStep>step 3</SliderStep>
</SliderSection>
<SliderSection>
<SliderStep>step 1</SliderStep>
</SliderSection>
<SliderSection>
<SliderStep>step 1</SliderStep>
<SliderStep>step 2</SliderStep>
</SliderSection>
</Slider>
there is a functionality inside both SliderSection
and SliderStep
which rely on the position of them inside the parent component(Slider
)
i used to pass down their position number as a prop to each component like this:
by using props called sectionNum
and stepNum
<Slider>
<SliderSection sectionNum={1}>
<SliderStep stepNum={1}></SliderStep>
<SliderStep stepNum={2}></SliderStep>
<SliderStep stepNum={3}></SliderStep>
</SliderSection>
<SliderSection sectionNum={2}>
<SliderStep stepNum={1}></SliderStep>
</SliderSection>
<SliderSection sectionNum={3}>
<SliderStep stepNum={1}></SliderStep>
<SliderStep stepNum={2}></SliderStep>
</SliderSection>
</Slider>
notice how sectionNum
starts from 1 and goes up for each SliderSection
, sliderNum
also starts from 1 and goes up for each SliderStep
inside SliderSection
and resets to 1 when SliderSection
changes and goes up.(basically first step of each section stepNum
is 1)
but this has some consequences beside not being automatic.
how can i get access to positions without manually passing props down?
why do i need this info inside SliderStep and SliderSection components?:
I want to be able to return null depending on some values(ex, don’t render step 2 if x is true) but since the sectionNum
and stepNum
props are hardcoded it will mess up the indexing of the slider so i need a way to handle this even if for example section#1-step#2 is not rendered internationally section#1-step#3 should change to section#1-step#2