To pass data from child to parent component in React:
At what situation we pass handler function from parent to child component in react?
Passing handler functions from a parent component to a child component in React is a common practice and serves several purposes:
Managing State: Parent components often have the responsibility of managing state, while child components may need to trigger changes in that state. Passing down handler functions allows child components to interact with and modify the parent’s state.
Communication: It enables communication between parent and child components. Child components can notify the parent component of specific events or user interactions, such as button clicks or form submissions.
Reusability: By passing handlers as props, you can create more reusable child components. These components can be used in different parts of your application while still interacting with the parent component in a consistent way.
Abstraction: It helps maintain a separation of concerns in your application. The child component doesn’t need to know how the state is managed or what other components are doing with it. It only needs to know how to call the handler when necessary.
Testing: When you pass handlers as props, it becomes easier to test your components. You can mock the handlers and simulate user interactions in unit tests for the child component.
Common scenarios where you might pass handler functions from a parent to a child component include:
Form Handling: When building forms, you pass down functions to handle form submissions, input changes, and validation from the parent component to the form child component.
Button Clicks: You might pass a function to handle button clicks, which can trigger actions or state updates in the parent component.
Modal Dialogs: For modal components, you can pass functions to open, close, or submit the modal from a parent component.
List Items: In a list component, you may pass a function to handle item selection or deletion back to the parent component.
Here’s a simple example to illustrate passing a handler function from a parent to a child component:
//1- ParentComponent.js
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const [message, setMessage] = useState('');
const handleMessageChange = (newMessage) => {
setMessage(newMessage);
};
return (
<div>
<h1>Parent Component</h1>
<ChildComponent onMessageChange={handleMessageChange} />
<p>Message from Child: {message}</p>
</div>
);
}
export default ParentComponent;
// 2-ChildComponent.js
import React, { useState } from 'react';
function ChildComponent({ onMessageChange }) {
const [inputMessage, setInputMessage] = useState('');
const handleInputChange = (e) => {
setInputMessage(e.target.value);
};
const handleButtonClick = () => {
// Call the parent's handler function with the new message
onMessageChange(inputMessage);
};
return (
<div>
<h2>Child Component</h2>
<input
type="text"
value={inputMessage}
onChange={handleInputChange}
placeholder="Type a message"
/>
<button onClick={handleButtonClick}>Send Message to Parent</button>
</div>
);
}
export default ChildComponent;
In this example, the ParentComponent passes the handleMessageChange function to the ChildComponent as the onMessageChange prop. When the button is clicked in the ChildComponent, it calls this prop function, which updates the state in the parent component, demonstrating how handler functions facilitate communication and state management between parent and child components.
—-
1.Pass a function as a prop to the Child component.
2.Call the function in the Child component and pass the data as arguments.
3.Access the data in the function in the Parent.
Functional Component
App.js (Example Functional Component)
import {useState} from 'react';
function Child({handleClick}) {
return (
<div>
<button onClick={event => handleClick(event, 100)}>
Click
</button>
</div>
);
}
export default function Parent() {
const [count, setCount] = useState(0);
const handleClick = (event, num) => {
console.log(event.target);
setCount(current => current + num);
};
return (
<div>
<Child handleClick={handleClick} />
<h2>Count: {count}</h2>
</div>
);
}
Class Component
Following are the steps to pass data from child component to parent component:
In the parent component, create a callback function. This callback function will retrieve the data from the child component.
Pass the callback function to the child as a props from the parent component.
The child component calls the parent callback function using props and passes the data to the parent component.
src/App.js:
import React from 'react';
import Child from './Child'
class App extends React.Component{
state = {
name: "",
}
handleCallback = (childData) =>{
this.setState({name: childData})
}
render(){
const {name} = this.state;
return(
<div>
<Child parentCallback = {this.handleCallback}/>
{name}
</div>
)
}
}
export default App
src/component/Child.js
import React from 'react'
class Child extends React.Component{
onTrigger = (event) => {
this.props.parentCallback(event.target.myname.value);
event.preventDefault();
}
render(){
return(
<div>
<form onSubmit = {this.onTrigger}>
<input type = "text"
name = "myname" placeholder = "Enter Name"/>
<br></br><br></br>
<input type = "submit" value = "Submit"/>
<br></br><br></br>
</form>
</div>
)
}
}
export default Child