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

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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