Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
Create the same ref functionality in React Function component as in React Class component

I would like to create the exact same behaviour in function component ref as there is in class component ref.

Heres an example:

const AnotherComponent = () => {
    const DoSomething () => console.log(something);
    return <div> There is a content </div>;
}

const MyComponent () => {
    let newRef = useRef();
    useEffect(() => {
        newRef.current.DoSomething();
    }, []);
    return <AnotherComponent ref={newRef} />;
}

I know about forwardRef, but from what I understand it allows you to bind the ref to a specific input to get its events, but not to the WHOLE component with all its functions.

Is it even possible to achieve this with function components ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Yes, it's completely possible. React refs are for more than just getting access to DOMNodes. Use a combination of React.forwardRef and the useImperativeHandle React hook to forward a React ref to a function component and expose out functions/values.

const AnotherComponent = React.forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    doSomething
  }));
  const doSomething () => console.log(something);
  return <div> There is a content </div>;
});

...

const MyComponent () => {
  const newRef = useRef();
  useEffect(() => {
    newRef.current.doSomething();
  }, []);
  return <AnotherComponent ref={newRef} />;
}

Forwarding refs

forwardRef

useImperativeHandle

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda