0

I want to create a component with only one event and place it inside an ancestor of any given level (child or grandchild or deeper), and when the event triggers the parent of this ancestor will act (eg. alert("I am "+parent.name+" and one of my ansestors did something")). Imagin of an old peoples home whos residents refuse to die and have a million ansestors, and the residents inform eachother everytime one of their ansestors has a birthday. What would be the most elgant way to do this since i understand that the observer pattern is fround upon in react? and could it be done without passing the parent object manually when creating a child?

Shai Kimchi
  • 746
  • 1
  • 4
  • 22

2 Answers2

0

One way I know how to do this is to pass a function down the "family tree" that does something in the parent

class Parent extends React.Component {
  constructor(props) {
    super(props)
    
    this.doSomethingInParent = this.doSomethingInParent.bind(this);
  }
  
  doSomethingInParent() {
    console.log('running in parent');
  }
  
  render() {
    return <Child parentsFunction={this.doSomethingInParent} />
  }
}

Now if you ran parentsFunction within the child component you would see the console.log inside doSomethingInParent. If you wanted to go deeper you would have to continually pass that function down through props which can get tedious in more complex applications. Which is why redux/flux is popular because it lets you manage state/dispatch actions and avoid long chains of callback functions.

  • Passing the function is indeed tedius, and the problem with flux/redux is that i couldnt figure out how to apply specific listeners to a closed group of components, if an ansestor sends out a message how can i register only its parent to listen. From what i understand all the parents will here the message. – Shai Kimchi Sep 24 '16 at 07:25
  • I could only do that using "contains" and React.findDOMnode. https://jsfiddle.net/shaibam/d0q5mwc4/33/ – Shai Kimchi Sep 24 '16 at 09:40
0

Solution was found using getChildContext , childContextTypes after discussion in : check if a component is a child or ancestor of another component ReactJS see example (for 2 solutions) : https://jsfiddle.net/shaibam/d0q5mwc4/33/.

contextTypes: {
    notifyChange: React.PropTypes.func
}.....
Community
  • 1
  • 1
Shai Kimchi
  • 746
  • 1
  • 4
  • 22