DEV Community

Cover image for Child ‘s function calling from parent component | ReactJS | NextJS
Abhijeet kumar
Abhijeet kumar

Posted on

Child ‘s function calling from parent component | ReactJS | NextJS

Hello dev 👋 ,

In this blog, we’ll explore to call the child component function from the parent component.

but before moving further, make sure that you’re using React version 17 or above.

So let’s get started.

We are assuming that we have a Parent component ApplyFilter.jsx and another child component Home.jsx.

//ApplyFilter.jsx (Child component)

import React, { forwardRef, useImperativeHandle } from "react";

const ApplyFilter = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    qtyIncrement: () => qtyIncrement(),
    qtyDecrement: () => qtyDecrement(),
    deleteHandler: () =>deleteHandler(),
  }));

  const qtyIncrement = () => {
    console.log("qtyIncrement");
    // ...
  };
  const qtyDecrement = () => {
    console.log("qtyDecrement");
    // ...
  };
  const deleteHandler = () => {
    console.log("deleteHandler");
    // ...
  };
  return 
(<div>
<h2>{props?.title}</h2>
<p>Other DOM</p>
</div>);
});

ApplyFilter.displayName = "ApplyFilter";
export default ApplyFilter;
Enter fullscreen mode Exit fullscreen mode

Let ‘s break down .

  1. Imports:
    import React, { forwardRef, useImperativeHandle } from "react";
    This imports React and necessary hooks (forwardRef and useImperativeHandle) from the "react" library.

  2. Function Component Definition:
    const ApplyFilter = forwardRef((props, ref) => {...});
    Defines a functional component named ApplyFilter.
    forwardRef() is used to forward the ref object from the parent component to this child component.

  3. useImperativeHandle Hook:
    useImperativeHandle(ref, () => ({...}));
    This hook allows the child component to expose certain functions to the parent component through the forwarded ref.

  4. Inside the callback, an object is returned containing functions (qtyIncrement, qtyDecrement, deleteHandler) which will be accessible from the parent component when using the ref.

  5. Function Declarations:
    const qtyIncrement = () => {...};, const qtyDecrement = () => {...};, const deleteHandler = () => {...};
    These are the functions declared within the component. which we have to call from parent which we have bind in a object.

  6. Return Statement:
    return (

    ...); This returns JSX elements representing the component’s UI. In this case, it returns a element containing an element with the title prop passed from the parent component, and a

    element with some placeholder text.

  7. ApplyFilter.displayName:
    ApplyFilter.displayName = "ApplyFilter";This sets the displayName property of the component, which can be useful for debugging or displaying in React DevTools.

  8. Export Statement:
    export default ApplyFilter;
    This exports the ApplyFilter component as the default export from this module, making it accessible for import in other files.

  9. Now have to import this child component ApplyFilter.jsx into Parent component and our parent component is Home.jsx where we ‘ll be access to call the ApplyFilter component ‘s functions.

    // home.jsx (Parent component)
    
    import React ,{useRef} from "react"
    import ApplyFilter from './ApplyFilter'
    
    export default function Home() {
      const childRef = useRef()
      return (
        <main>
          <ApplyFilter title={'Filter'} ref={childRef} />
          <button onClick={() => {
            childRef.current.qtyIncrement()
          }}>+</button>
          <button onClick={() => {
            childRef.current.qtyDecrement()
          }}>-</button>
          <button onClick={() => {
            childRef.current.deleteHandler()
          }}>
            RESET
          </button>
        </main>
      )
    }
    

    As we can see, there are three functions: qtyIncrement, qtyDecrement, and deleteHandler, which we are accessing using the useRef hook passed as props to the ApplyFilter component.

    Conclusion — we’ve explored the process of calling a child component function from a parent component in a React application. By leveraging the useImperativeHandle hook along with the forwardRef function, we've established a way for the child component to expose specific functions to the parent component through a forwarded ref.

Top comments (0)