Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
How to access a child component (from props.children) ref using functional components

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!