How to reference a function in another component in React

When referencing a function in another component in React, it is a common practice to pass a function as a prop or to use a state management system, such as Redux, Mobx, or Context API. In this Answer, we’ll cover a broad illustration of this using the React framework, but the idea can also be used with other frameworks.

Assuming we have two components, ComponentA and ComponentB, the steps to reference a function from them are described below,

Passing the function as a prop

In ComponentA, we define the function and then pass it as a prop to ComponentB, as shown below:

import React from 'react';
function ComponentA(props) {
const handleClick = () => {
// Your function logic
};
return (
<div>
<ComponentB onClickFunction={handleClick} />
</div>
);
}
export default ComponentA;

In the above widget, we define the handleClick in ComponentA and pass it to ComponentB as the onClickFunction.

Receiving the prop in ComponentB

In ComponentB, we receive the function as a prop and use it as needed. Here’s an example:

// ComponentB.jsx
import React from 'react';
function ComponentB(props) {
const { onClickFunction } = props;
return (
<button onClick={onClickFunction}>Click me</button>
);
}
export default ComponentB;

In the above widget, when the button in ComponentB is clicked, the onClickFunction from ComponentA is called.

Usage in a parent component

If ComponentA and ComponentB are both used in a parent component, we include them as follows:

// ParentComponent.jsx
import React from 'react';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
function ParentComponent() {
return (
<div>
<ComponentA />
<ComponentB />
</div>
);
}
export default ParentComponent;

This allows us to use both ComponentA and ComponentB within a parent component.

Let’s see the following running example:

// ComponentB.jsx
import React from 'react';

function ComponentB(props) {
  return (
    <div>
      <h2>Component B</h2>
      {props.children}
    </div>
  );
}

export default ComponentB;
Function referencing in the components

Code explanation

We use ComponentA to define a handleClick function that displays an alert when the button is clicked. On the other hand, ComponentB doesn’t have its own function but can receive child components. The main application component, App, renders ComponentA and ComponentB. It also defines the handleFunctionCall function to demonstrate calling a function in ComponentA from ComponentB.

When we click the Call Function in ComponentA button in ComponentA, it triggers the handleClick function. When we click the Call Function in ComponentA from ComponentB button in ComponentB, it triggers the handleFunctionCall function in the App component, which demonstrates how to reference a function from ComponentA in ComponentB.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved