I'm trying to use an IntersectionObserver.observe() on every single child component from a parent component, but for that I need their refs.
This is what my main component looks like:
// App component
<Nav>
<Section ref={useRef(null)} {/* other props */} />
<Section ref={useRef(null)} {/* other props */} />
<Section ref={useRef(null)} {/* other props */} />
<Section ref={useRef(null)} {/* other props */} />
</Nav>
I need the Nav component to access the ref of each Section component. I created the observer and got all children elements on a list:
// Nav component
const observer = new IntersectionObserver(observerCallback, options);
const sectionList: ReactElement<SectionProps>[] = [];
childrenToList(props.children, sectionList);
return (
<>
<nav className="nav">
{/* ... */}
</nav>
{sectionList}
</>
)
// Section component
const Section = React.forwardRef<HTMLDivElement, SectionProps>((props, ref) => {
return (
<section ref={ref} {/* other attributes */}>{props.children}</section>
);
});
This is what the childrenToList function is doing:
function childrenToList(children: ReactNode, listToPush: any[]) {
React.Children.forEach(children, (element) => {
if (!React.isValidElement(element)) return;
listToPush.push(element);
});
}
Then I need a way to do something like that (not an actual working code):
sectionList.forEach((section) => {observer.observe(section.ref.current)})
The problem is that I couldn't find a way to access the ref. I already tried having the ref as a prop, but it said it's value is null, or if I used with an if statement (like
const ref = section.props.ref
if (ref) {
observer.observe(ref.current)
}
) the page simply wouldn't render and would remain blank.