← Home

Call Child Component Method from Parent in React

June 27, 2021

We can call methods or functions located inside a child component simply using references which is supported on class components and recently on functional components using hooks.

React Refs (references) provide an esay way to access DOM nodes or React elements created in the render method, which differentiate from the react data flow using states and props.

Call a child class method for parent

Consider the following child component that contains a method foo which simply alerts a Hello world message.

class Child extends React.Component {

  // The child method foo
  foo() {
    alert("Hello world")
  }

  render() {
    return <div>Child content</div>
  }
}

In our parent component we are going to render the Child component and call its method foo.

class Parent extends React.Component {

  constructor(props) {
    super(props)

    // Create the child instance using react createRef
    this.child = React.createRef()
  }

  handleClick = () => {

    // Call the child method foo
    this.child.current.foo()
  }

  render() {
    return (
      <>
        <Child ref={this.child} />
        <button onClick={this.handleClick}>
          Call foo
        </button>
      </>
    )
  }

React.createRef() creates the component reference variable which is attached to our child element via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

For functional components

In a function component we need to make a custom implementation using forwardRef and useImperativeHandle to make the Refs works.

const Child = React.forwardRef((props, ref) => {

  React.useImperativeHandle(ref, () => ({
    foo() {
      alert("Hello world")
    }
  }))

  return <div>Child content</div>
})

The parent’s functional component:

function Parent() {

  // Create the child instance with useRef hook
  const child = useRef();

  const handleOnClick = () => {
    if (child.current) {
      child.current.foo();
    }
  }

  return (
    <>
      <Child ref={child} />
      <button onClick={handleOnClick}>Call foo</button>
    </>
  )
}

The demo above was a good way to use Refs, but if you’ve ever thought refrences would solve all your problems, take a moment and think, maybe only the default react data flow can solve your problem.

Here are other good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries

Chafik Gharbi Full-stack web and mobile app developer with JavaScript. @gharbichafik