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

159
Visualizações
in a nextjs app, how do I trigger a function in one component from another

Just like the title says, I've got 2 custom components on a page in a simple NextJS application:

<section>

   <CompA></CompA>
   <CompB></CompB>

</section>

How can I have a button in CompB trigger a function contained in CompA?

I assume I should use state somehow, but I'm a little lost how to do that in NextJS. Simple code example here: https://github.com/Chenzo/nextjs-comp-to-comp

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

0

Technically, you can do this with the useImperativeHandle hook, but this is not exactly the "React way":

const CompA = forwardRef(({ children }, ref) => {
  useImperativeHandle(ref, () => ({
    doSmth: () => {
      console.log('CompA - function');
    },
  }));

  return (
    <div>
      <h2>Component A</h2>
    </div>
  );
});

const CompB = ({ onClick }) => {
  return (
    <div>
      <h2>Component B</h2>
      <button onClick={onClick}>Trigger CompA function</button>
    </div>
  );
};

export default function Home() {
  const compARef = useRef();
  const handleCompBClick = useCallback(() => compARef.current?.doSmth(), []);

  return (
    <section>
      <CompA ref={compARef}></CompA>
      <CompB onClick={handleCompBClick}></CompB>
    </section>
  );
}

As I wrote above, there is most likely a more correct way to solve your problem, avoiding the imperative approach. The decision will depend on what exactly components A and B will do in a real application.

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