1

I am creating a ReactJS Component with an unknown number of children and ancestors, and when a certain event occurs on one of the ancestors I the parent component should know of it. my first approach is to use redux and send the child component with a redux action, and then main parent componetnts will be alerted and will check if the Componetnt sent was one of its ancestors. but, can a parent reactJS component know in someway if another component is one of its ancestors?

Shai Kimchi
  • 746
  • 1
  • 4
  • 22
  • the only way I can see this done is by using js/DOMelemt 'contains' with React.findDOMelement. https://jsfiddle.net/shaibam/d0q5mwc4/33/ – Shai Kimchi Sep 24 '16 at 09:39

1 Answers1

1

The parent can define a function in the context, Children can then call this function:

Parent:

childContextTypes: {
    notifyChange: React.PropTypes.func.isRequired
},

getChildContext () {
    return {
        notifyChange: (...args) => this.handleChange(...args)
    }
},

handleChange (arg) {
    console.log(arg + ' bar!')
},

Child:

contextTypes: {
    notifyChange: React.PropTypes.func
},

handleSomething () {
    const { notifyChange } = this.context

    // safety check if component is used elsewhere
    if (notifyChange) notifyChange('foo!')
},
Rick
  • 508
  • 4
  • 9
  • Thank you very much, I've updated the filddle to include your solution. https://jsfiddle.net/shaibam/d0q5mwc4/35/ – Shai Kimchi Sep 24 '16 at 12:36