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

114
Visualizações
How can I access methods of a component using ref in functional component

I am trying to access a component method using createRef() however i am getting TypeError: modalRef.current is null error back.

I never used refs before so if its wrong guide the way how to achieve what I am trying to do.

this is my try

const parent = () => {
  const modalRef = createRef();
  const onBtnClick = () => {
   modalRef.current.upadeState();
  }
  return(
  <div>
   <button onclick={onBtnClick}>bro</button>
    <Modal ref={modalRef} />
  </div>
 )
}

Modal

export default Modal = () => {
  const upadeState = () => {
   console.log('It works fam');
   }
  return(
  <div>
    bro we here
  </div>
 )
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

For calling Child Component method from parent component in hooks we are using React.forwardRef and React.useImperativeHandle hooks from React.

Here is an example to call the child method.

Child.js

import React from "react";
const { forwardRef, useState, useImperativeHandle } = React;

// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Child = forwardRef((props, ref) => {
  const [state, setState] = useState(0);

  const getAlert = () => {
    alert("getAlert from Child");
    setState(state => state + 1)
  };

  // The component instance will be extended
  // with whatever you return from the callback passed
  // as the second argument
  useImperativeHandle(ref, () => ({
    getAlert,
  }));

  return (
    <>
      <h1>Count {state}</h1>
      <button onClick={() => getAlert()}>Click Child</button>
      <br />
    </>
  );
});

Parent.js

import React from "react";
const { useRef } = React;

export const Parent = () => {
  // In order to gain access to the child component instance,
  // you need to assign it to a `ref`, so we call `useRef()` to get one
  const childRef = useRef();

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.getAlert()}>Click Parent</button>
    </div>
  );
};

Child component is rendered and a ref is created using React.useRef named childRef. The button we created in the parent component is now used to call the child component function childRef.current.getAlert();

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