hegdeashwin hegdeashwin - 1 month ago 16
React JSX Question

Children to children components communication

I have 1 parent component name [Parent-1] and 1 child component name [Child-1]. Now, I have few more other components name [Other-1] and [Other-2].

Now i am passing [Other-1] and [Other-2] component to [Child-1] component. JSX is rendering correct. How can i access [Other-1/2] component functions from [Child-1] ? or How can i pass props to [Child-1] from [Other-1/2] ?

By using refs I am able to call the [Other-1/2] functions from [Parent-1] but I want to access from [Child-1]. I tried passing refs to [Child-1] like

<Child abc={() => this.refs.other1.hello()}/>
or
<Child abc={this.refs.other1.hello()}/>
but this is not working.

By using global Event Emitter way I am able to achieve solution to my above problem. But not sure if that's the appropriate way in React.js

Answer

I think you're not using the refs properly.

When you try to give an arrow function to refs it will sometime causes error due to the ref returning null. See my question to find out why.

The example should help you understand refs

Hope this helps!

class Others1 extends React.Component {
  log(){
    console.log('Hello from Others1')
  }
  render() {
    return <h1>Others1</h1>
  }
} 

class Others2 extends React.Component {
  log(){
    console.log('Hello from Others2')
  }
  render() {
    return <h1>Others2</h1>
  }
} 


class Child extends React.Component{
  other1Ref(el) {
    el.log()
  }
  other2Ref(el) {
    el.log()
  }
  render() {
    const Others1 = this.props.others1
    const Others2 = this.props.others2
    return (
      <div>
       <Others1 ref={this.other1Ref}/>
       <Others2 ref={this.other2Ref}/>
      </div>
    )
  }
  
}

class Parent extends React.Component{
  render() {
    return <Child others1={Others1} others2={Others2}/>
  }
}

ReactDOM.render(<Parent/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>