React 03: Passing Data from Child to Parent Component in React ๐
PREVIOUS BLOG:
React 02: React Components and Props ๐
Props in React are typically used to pass data from parent components to child components. However, there are scenarios where you need to pass data from a child component back to its parent. This is achieved through callback functions passed as props. Letโs break down how this works with an example! ๐
App Component ๐
In your App
component, you define a function that will handle the data coming from the child component. This function is then passed as a prop to the child component.
import React from "react";
import "./style.css";
import ChildComponent from "./components/child-parent";
export default function App() {
const text = "React Props";
const parentFunc = (data) => {
console.log("Receiving the ", data);
};
return (
<div>
<h1>Hello React</h1>
<ChildComponent funcPass={parentFunc} />
</div>
);
}
Here, parentFunc
is a function that logs the data it receives. This function is passed to ChildComponent
as a prop named funcPass
.
ChildComponent ๐ง
In your ChildComponent
, you call the function received via props when a certain event occurs (e.g., a button click).
import React from "react";
function ChildComponent({ funcPass }) {
const callFunc = () => {
funcPass("Sending...");
};
return (
<div>
<button onClick={callFunc}>Call Me from Child</button>
</div>
);
}
export default ChildComponent;
In this example, funcPass
is called with the argument "Sending..."
when the button is clicked. This triggers the parentFunc
in the App
component, logging the message to the console.
How It Works ๐
- Define a Callback Function in the Parent: The parent component defines a function (
parentFunc
) to handle data from the child. - Pass the Function as a Prop: This function is passed to the child component via props.
- Invoke the Function in the Child: The child component invokes the function when needed, passing the data as arguments.
- Parent Receives the Data: The parent componentโs function executes, handling the data received from the child component.
Why Use This Pattern? ๐ค
This pattern is useful when:
- The child component needs to notify the parent about certain events.
- The parent component needs to update its state or perform some action based on the childโs input.
Example Use Cases:
- Forms where child components (input fields) need to report their values back to the parent component.
- UI elements like buttons or sliders that need to control or affect the parent componentโs state.
STACKBLITZ LINK
https://stackblitz.com/edit/react-child-to-parent-component
Conclusion ๐
Passing data from child to parent components in React is a common pattern achieved by using callback functions. This allows for more interactive and dynamic applications, where components can communicate effectively, ensuring a seamless flow of data and functionality.