I have a PagesContainer
component that renders multiple Page
components like this:
<PagesContainer>
<Page />
<Page />
<Page />
<Page />
</PagesContainer>
I want each Page
component to know its respective page number (e.g., 1, 2, 3, 4).
I preferably do not want to pass it down as a prop (e.g., <Page number={1} />
) because I will be programatically generating some <Page />
through loops, but not all of them. I also want to be able to reorder these pages freely and have each render the right number just by moving its position in the parent.
Ideally, I’d like a hook like so: const currentPage = useGetCurrentPage()
.
How do I get the <Page />
‘s position in the parent?
2
Answers
You can
map()
over theprops.children
, then use theindex
frommap
to pass along to the Child usingcloneElement
.I’ve incremented the
index
by1
since your example does not start from0
.You can use a forwardRef and useImperativeHandle and useState.