How To Pass Value From A Child Functional Component To Parent Class Component?
I have a parent class component and a child functional component. How can we pass value from this type of child component to parent component - I have seen some examples that passe
Solution 1:
Parent component
importReactfrom"react";
importChildComponentfrom"./ChildComponent/ChildComponent";
classParentComponentextendsReact.Component {
constructor(props) {
super(props);
this.state = {
data: [] // An index value is in this state
};
}
handleClick = (value) => {
// handle changes from childconsole.log(value)
}
render(){
return(
<React.Fragment>
// 1. we pass function for child on props
<ChildComponenthandleClick={this.handleClick}indexval = {this.state.data.index} /></React.Fragment>
)
}
}
exportdefaultParentComponent;
Child component
importReactfrom'react';;
importButtonfrom'./Button/Button';
functionChildComponent(props) {
constnewVal=(index) => {
let retVal = index + 1;
// 2. do calculations and send it to parent
props.handleClick(retVal);
}
return (
<React.Fragment><ButtononClick={() => newVal(props.index)}>Click</Button></React.Fragment>
)
}
Solution 2:
This is sample to show how you can work with parent and child component.
classParentextendsReact.Component {
state={name:"Hello"}
handleClick = () => {
this.setState({name:"Welcome to the world of React."})
};
render() {
return (
<divclassName="App"><Childname={this.state.name}handleClick={this.handleClick} /></div>
);
}
}
functionChild({name, handleClick}){
return (
<div><h2>{name}</h2><buttononClick={handleClick}>Change</button></div>
)
}
Solution 3:
You can pass a dispatcher to the child component which in turn can call this dispatcher to pass the value you want to:
Parent class component:
importReactfrom"react";
importChildComponentfrom"./ChildComponent/ChildComponent";
classParentComponentextendsReact.Component {
constructor(props) {
super(props);
this.state = {
data: [] // An index value is in this state
};
this.updateParentState = this.updateParentState.bind(this);
}
// dispatcher to pass as a propupdateParentState(val){
this.setState({index:val});
}
render(){
//can console log the return value from the ChildComponent here if needed return(
<React.Fragment><ChildComponentindexval = {this.state.data.index}updateParent={this.updateParentState} /></React.Fragment>
)
}
}
exportdefaultParentComponent;
Child component:
importReactfrom'react';
importButtonfrom'./Button/Button';
functionChildComponent(props) {
constnewVal=() => {
return props.index + 1; //do it this way
}
return (
<React.Fragment><ButtononClick={() => props.updateParent(newVal())}>Click</Button></React.Fragment>
)
}
exportdefaultChildComponent;
Post a Comment for "How To Pass Value From A Child Functional Component To Parent Class Component?"