child to parent component react code example
Example 1: pass data from child component to parent component react native
class Parent extends React.Component {
state = { message: "" }
callbackFunction = (childData) => {
this.setState({message: childData})
},
render() {
return (
<div>
<Child1 parentCallback = {this.callbackFunction}/>
<p> {this.state.message} </p>
</div>
);
}
}
class Child1 extends React.Component{
sendData = () => {
this.props.parentCallback("Hey Popsie, How’s it going?");
},
render() {
}
};
Example 2: communication child to parent react js
import React from 'react';
import Child from './Child'
export default class Parent extends React.Component {
constructor(props){
super(props);
this.state ={ text:''};
}
handleChangeInParent = (event) => {
this.setState({text:event.target.value})
}
render() {
return (
<>
<p>You have written: </p>
<p>{this.state.text}</p>
<Child handleChange={this.handleChangeInParent}/>
</>
)
}
}
Example 3: pass element from child to parent react
Parent:
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
Child:
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}