Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda