1class Parent extends React.Component {
2 state = { message: "" }
3 callbackFunction = (childData) => {
4 this.setState({message: childData})
5 },
6 render() {
7 return (
8 <div>
9 <Child1 parentCallback = {this.callbackFunction}/>
10 <p> {this.state.message} </p>
11 </div>
12 );
13 }
14}
15
16class Child1 extends React.Component{
17 sendData = () => {
18 this.props.parentCallback("Hey Popsie, How’s it going?");
19 },
20 render() {
21 //you can call function sendData whenever you'd like to send data from child component to Parent component.
22 }
23};
1Parent:
2
3<div className="col-sm-9">
4 <SelectLanguage onSelectLanguage={this.handleLanguage} />
5</div>
6
7Child:
8
9handleLangChange = () => {
10 var lang = this.dropdown.value;
11 this.props.onSelectLanguage(lang);
12}
1class ToDoList extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = {
5 listDataFromChild: null
6 };
7 },
8 myCallback = (dataFromChild) => {
9 this.setState({ listDataFromChild: dataFromChild });
10 },
11 otherFn = () => {
12 [...within this other function now I still have access to this.state.listDataFromChild...]
13 }
14 render() {
15 return (
16 <div>
17 <ToDoItem callbackFromParent={this.myCallback}/>
18 [...now here I can pass this.state.listDataFromChild as a prop to any other child component...]
19
20 </div>
21 );
22 }
23});