React – Parent Component Calling a Child Component Method

Photo by Eddie Galaxy from Pexels

Overview

This post will go over common scenarios of a Parent Class Component calling a method in a Child Component. Warning! The code examples are with JavaScript, not TypeScript.

Parent Class Component calling a method in a Child Class Component.

Parent Class Component Calling Child Class Component

From the Parent Component

import ChildComponent from '../ChildComponent';
...
export default class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this._child = React.createRef();

Rendering the child component add the reference

<ChildCOmponent ref={this._child} />                                    

Child Component

onLoadData = (event) => {
   // ... Function code
   alert('Called Child Component Method');
}

Parent Class Component.

Use React.createRef() to establish a reference. Adding onRef={ref => (this.ChildClassComp = ref)} will pass a reference to the child component.

import React from 'react'
import ChildClassComp from './ChildClassComp';

class ParentClassComp extends React.Component {

  constructor(props) {
    super(props);
    this.ref = React.createRef();    

  }

  
triggerClassChildAlert = () => {
    this.ChildClassComp.showAlert();
    
  };

  
  render() {
    return (
      <React.Fragment>
        <div className="row">
          <div className="col-12">
            <button className="btn btn-primary" onClick={() => {this.triggerClassChildAlert()}}> Child Class Comp Alert</button>
          </div>
        </div>
        <div className="row">
          <div className="col-12">
            <ChildClassComp onRef={ref => (this.ChildClassComp = ref)}/>            
          </div>
        </div>
              
      </React.Fragment>
    )
  }
}

export default ParentClassComp

Child Class Component Calling Hook Component.

In the Child Class Component use the componentDidMount() and componentWillUnmount() events to set up and release a reference with this.props.onRef();

import React from 'react'

class ChildClassComp extends React.Component {

  constructor(props) {
    super(props);
  }
  
  componentDidMount() {
    this.props.onRef(this)
  }
  
  componentWillUnmount() {
    this.props.onRef(undefined)
  }

  showAlert = () => {
    alert('Child Class Component');
  }

  render() {    
    return (
      <React.Fragment>
        Child Class Comp
      </React.Fragment>
    )
  }
}

export default ChildClassComp

Parent Class Component calling a method in a Child Hook Component.

Parent Class Component.

The Parent will be identical to the Class Component in the first example.

import React from 'react'
import ChildHook from './ChildHook';

class ParentClassComp extends React.Component {

  constructor(props) {
    super(props);
    this.ref = React.createRef();    

  }

  triggerFuncChildAlert = () => {
    this.ref.current.showAlert();

  };
  
  render() {
    return (
      <React.Fragment>
        <div className="row">
          <div className="col-12">
          <button className="btn btn-primary" onClick={() => {this.triggerFuncChildAlert()}}> Child Comp Method Call</button>
          </div>
        </div>
        <div className="row">
          <div className="col-12">
            <ChildHook ref={this.ref}/>
          </div>
        </div>
              
      </React.Fragment>
    )
  }
}

export default ParentClassComp

Child Component (Hook)

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

const ChildHook = forwardRef((props, ref) => {
    useImperativeHandle(
        ref,
        () => ({
            showAlert() {
                alert("Child Method Called")
            }
        }),
    )
    return (
       <div>Child Component</div>
    )
});

export default ChildHook;