Parent Child communication seems no problem using pass props:
mainpage.ios.js code:
var OtherPage = require('./otherpage');
<OtherPage value={2}/>
Then on otherpage.ios.js I can utilise the variable using this.props.value but then if I update the value on otherpage.ios.js how does it get communicated back to the mainpage.ios.js?
React. js allows us to use props (short form of property) to pass data from parent component to child component. We have to set props value inside the child component, while we embed it to the parent component.
You can't pass props from child to parent in React, it's only one way (from parent to child). You should either: Put the state in the parent component and manipulate it from the child component by passing the setter function in the props.
You would pass a callback then pass it through props, likely utilizing the componentWillReceiveProps hook as your setup gets more advanced.
If you are doing this alot then yes, you should be using Flux or Redux or similar.
import React, {
Component,
TouchableOpacity,
Text,
} from 'react-native';
class Main extends Component {
constructor() {
super();
this.state = {
data: 'default'
}
}
onChange = (data) => {
console.log(`Data changes to ${data} !`);
this.setState({ data });
}
render() {
const { data } = this.state;
return <Other data={data} onChange={this.onChange}></Other>;
}
}
class Other extends Component {
render() {
const { data } = this.props;
console.log(`Other Component Data is ${data}`);
return (
<TouchableOpacity onPress={() => {this.props.onChange('Success!')} }>
<Text style={{fontSize: 30}}>{data}</Text>
</TouchableOpacity>
);
}
}
Additionally, if you utilize Static Components when you know state is not needed in the secondary component, you can build much more re-useable functional components:
class Main extends Component {
constructor() {
super();
this.state = {
data: 'default'
}
}
onChange = (data) => {
console.log(`Data changes to ${data} !`);
this.setState({ data });
}
render() {
const { data } = this.state;
return <Other data={data} onChange={this.onChange}></Other>;
}
}
const Other = ({ data, onChange }) => {
return (
<TouchableOpacity onPress={() => {onChange('Success!')} }>
<Text style={{fontSize: 30}}>{data}</Text>
</TouchableOpacity>
);
}
EDIT These days you should probably only use functional components and hooks, there is much documentation on the React websites on this, but the idea is similar :-)
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