I am a beginner to the react native environment. I want to understand parent child communication in react native.
Parent will pass a number to a child - As an example parent pass "2" to a child.
Child will have a processing function which multiple the same number 2 times and return the result back to parent. - As example 2*2 and return
parent will call child function and see if output if correct and print results on parent container
if I would have done this in a programming lang like c++ or java.
*
parent.number = 2; parent.result = child.getResult(parent.number); if(parent.result == 4){ Print "child return correct value"; }else{ child return wrong value. }
*
I have seen couple of react native tutorials online but, still this parent child communication is not clear.
Can someone please code 2 react native js file one for parent and one for a child and show me the communication.
Thanks
It is done by passing callbacks/handlers to child component, here is an example. I have not tested it though.
Parent.js
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Child from './Child.js';
export default class Parent extends Component {
constructor() {
super();
this.state = {
result: 0
};
}
getResponse(result){
this.setState({result});
}
render(){
return (
<View>
<Text>{this.state.result}</Text>
<Child num={2} callback={this.getResponse.bind(this)}>
</View>
);
}
}
Child.js
import React, { Component } from 'react';
import { Button } from 'react-native';
export default class Child extends Component {
calc(){
this.props.callback(this.props.num * 2);
}
render(){
return (<Button onPress={() => this.calc()} title="Calc" />)
}
}
These are some recommended readings to understand better react https://facebook.github.io/react/docs/thinking-in-react.html https://facebook.github.io/react/docs/lifting-state-up.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With