Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!