Invoking Component Methods from Outside in Next.js

In Next.js, if you want to call methods defined within a component from outside, you can use React's useRef hook to reference the component instance and invoke its methods. This approach is primarily used with class components but can also be applied to functional components by exposing methods on the ref object.

Here is an example demonstrating how to call a method inside a component in Next.js:

Example Code

1. Create a Child Component and Expose Methods
// ChildComponent.tsx
import React, { useImperativeHandle, forwardRef, useState } from 'react';

interface ChildProps {
  // Define props types for the child component (if any)
}

export interface ChildRef {
  triggerAction: () => void;
}

const ChildComponent = forwardRef<ChildRef, ChildProps>((props, ref) => {
  const [value, setValue] = useState(0);

  useImperativeHandle(ref, () => ({
    triggerAction() {
      setValue(value + 1);
      console.log('triggerAction called');
    }
  }));

  return (
    <div>
      <p>Value: {value}</p>
      <button onClick={() => setValue(value + 1)}>Increase</button>
    </div>
  );
});

export default ChildComponent;
2. Reference and Call the Child Method from the Parent Component
// pages/index.tsx
import React, { useRef } from 'react';
import ChildComponent, { ChildRef } from '../components/ChildComponent';

const Home: React.FC = () => {
  const childRef = useRef<ChildRef>(null);

  const handleTrigger = () => {
    if (childRef.current) {
      childRef.current.triggerAction();
    }
  };

  return (
    <div>
      <h1>Next.js Parent Component</h1>
      <button onClick={handleTrigger}>Invoke Child Action</button>
      <ChildComponent ref={childRef} />
    </div>
  );
};

export default Home;

Explanation

  1. Child Component (ChildComponent.tsx):
    • Utilizes forwardRef and useImperativeHandle to expose internal methods to the parent component.
    • useImperativeHandle takes a ref and a factory function that returns an object containing the methods to expose.
    • In this example, triggerAction is the method exposed to the parent component.
  2. Parent Component (pages/index.tsx):
    • Uses useRef to create a reference to the child component childRef.
    • Passes childRef as the ref prop to the child component.
    • In the button's onClick handler, it calls the triggerAction method on the child component through childRef.

Summary

Using useRef and useImperativeHandle, you can call methods inside a component from outside in a Next.js application. This technique is particularly useful when you need to access or manipulate the state or methods of a child copmonent.

Tags: React Next.js Component Communication useRef useImperativeHandle

Posted on Thu, 18 Jun 2026 16:34:47 +0000 by sincejan63