Open In App

How to Call Parent Components’s Function from Child Component in React ?

In React, it is very important to manage communication between components for building flexible and maintainable applications. Sometime, you need to trigger a function defined in a parent component from a child component. In this article, we’ll see how to achieve this in React by passing down functions as props from parent to child components.

The Need for Calling Parent Functions from Child Components

In React, components are arranged in a way to be modular and reusable. However, there are situations where you need to perform actions or trigger functions defined in a parent component from its child components. This can be done whenwe want to handle user interactions, update state, or executing business logic that resides in the parent component.

Passing Functions as Props

One of the core principles of React is the concept of props, which are properties passed from parent components to their children. Along with data, you can also pass functions as props from parent to child components. By doing so, child components gain access to these functions and can invoke them when necessary.



Approach to Call Parent Component function from Child Component:

Example: Create the files as shown in folder structure and add the following codes.




/* App.css */
 
* {
    margin-left: 10px;
}
 
button {
    background-color: blue;
    padding: 10px 15px;
    color: #fff;
}
 
.parent {
    width: 27vw;
    height: 22vh;
    border: 1px solid black;
    padding-top: 20px;
    text-align: center;
}




//App.js
 
import { useState } from "react";
import "./App.css";
import Child from "./Child";
 
function App() {
    const [showDescription, setShowDescription] = useState("");
    function handleShowDescription(e) {
        console.log("calling from child component");
        setShowDescription(e);
    }
    return (
        <div className="App">
            <h2>Welcome to React Learning</h2>
            <div className="parent">
                <h3>Parent Window</h3>
                <p>{showDescription}</p>
                <Child callFunction={handleShowDescription} />
            </div>
        </div>
    );
}
 
export default App;




//Child.js
 
function Child({ callFunction }) {
 
    function handleClick() {
        callFunction("I'm the information from child component",)
    }
 
    return (
        <div>
            <button onClick={(e) =>
                handleClick()}>Child Button Click</button>
        </div>
    )
}
 
export default Child;

Output:

http://loclahost:3000


Article Tags :