Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save akinadebowale/aff9b29cd9939af0a6a03bd21d423cea to your computer and use it in GitHub Desktop.

Select an option

Save akinadebowale/aff9b29cd9939af0a6a03bd21d423cea to your computer and use it in GitHub Desktop.
React components talking / grandchild to child to parent.
import React from "react";
import { TouchableHighlight } from "react-native";
export class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null
};
// Remember to bind methods.
this.setValue = this.setValue.bind(this);
}
// Parent callback.
setValue(value) {
// Do what you want with the data.
this.setState({
value: value
});
}
render() {
// Parent "setValue" callback will receive "value" data from Child.
return <Child value={this.setValue} />;
}
}
export class Child extends Component {
constructor(props) {
super(props);
this.state = {};
// Remember to bind methods.
this.setValue = this.setValue.bind(this);
}
// Child (also a parent) callback.
setValue(value) {
// Sets data for the its prop: "value", which then sets data for the Parent's callback "setValue".
this.props.value(value);
}
render() {
// Child (also Parent to Grandchild) "setValue" callback will receive "value" data from Grandchild.
return <Grandchild value={this.setValue} />;
}
}
export class Grandchild extends Component {
render() {
// On action, set data for the its prop: "value", which then sets data for the Child's (its parent) callback "setValue".
return <TouchableHighlight onPress={ () => {this.props.value(9)} } />;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment