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,
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
.
ComponentB
In ComponentB
, we receive the function as a prop and use it as needed. Here’s an example:
// ComponentB.jsximport 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.
If ComponentA
and ComponentB
are both used in a parent component, we include them as follows:
// ParentComponent.jsximport 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;
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