DEV Community

Shin-Young Jung
Shin-Young Jung

Posted on • Updated on

Call Child Component's Functions From Parent Component

Sometimes, we want to call functions from child components. It's easier to call the parent's function by sending the function as a property, but to call the child component's function is a bit tricky. In most cases, if we design the component properly with SOLID patterns, there are not many chances to face this situation.

1. Using forwardRef and useImperativeHandle

You can wrap the Component that you want to access with forwardRef and define useImperativeHandle


    import React, {
      forwardRef,
      useImperativeHandle
    };

    const TestComponent = forwardRef((variables, ref) => {

      useImperativeHandle(ref, () => ({

        customFunc() {
          // do what you want here: you can return value 
          // or call function inside of the TestComponent
        }
      }))

      return <div > Hello < /div>;

    })
Enter fullscreen mode Exit fullscreen mode

and from another component,

    import React, {useRef} from 'react';

    const AnotherComponent = () => {
      const compRef = useRef();


      return <div role="none" onClick={() => {
      // this func() will be replaced the function that you defined in the
      // useImperativeHandle from the TEstComponent
      compRef.func()
      }}>
        <TestComponent ref={compRef} />
      </div>
    }


Enter fullscreen mode Exit fullscreen mode

2. Using React.useEffect and React.State

You can update the state from the Parent Component and pass that state variable to the component that you want to receive.


    import React, {
      useEffect,
      useState
    } from 'react';

    // Parent Component 
    const ParentComponent = () => {
      // better to use object due to refresh the variable
      const [state, setState] = useState(null);




      return <div role="none" onClick={() => {
        // if you click the parent component it will update state
        // and when the state is updated, then the Child Component will 
        // receive the update from the useEffect
        setState({update: 'update'});
      }}> 
              <ChildrenComponent update={state} /> 
             </div>;

    }

    const ChildComponent = ({update}) => {

    useEffect(() => {
    // this will be called whenever the update object is changed
    // so you can put something here to update the Child Component's state
    }, [update])

    return <div>Child</div>

    }
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
quantaoluo profile image
quantaoluo

very good