0

I am currently trying to get the child component functions using the ref in the following way but it doesn't show any of the details.

class ChildCompent extends React.Component {
  constructor(props){
    super(props);
  }

  _function1 =()=>{
     /* ...... */
  }

  _function1 =()=>{
    /* ...... */
  }
  render (){
     return (
        <div>
            ChildComponent
        </div>
    )
  }
}

let ComposedChild = compose(
  /* --- graphql query */
)(ChildComponent);



class ParentComponent extends React.Component {
   constructor(props){
     super(props);
   }

   _onClick = ()=>{
      console.log(this.refs.childComponent)
      // doesn't show the _function1 and _function2
   }

   render (){
      return (
          <div onClick={this._onClick}>
              <div>Testing</div>
              <ChildComponent ref="childComponent"/>    
          </div>        
     )
  }
}
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
Sai Ram
  • 4,196
  • 4
  • 26
  • 39

1 Answers1

0

You should make use of ref callback to set ref on a component See this answer:

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

After that to access another component's function you can do that like this.childComponent._function1()

Also you need to make use of the component returned after wrapping it with the compose function in the ParentComponent.

class ChildComponent extends React.Component {
  constructor(props){
    super(props);
  }

  _function1 =()=>{
     /* ...... */
     console.log('hello');
  }


  render (){
     return (
        <div>
            ChildComponent
        </div>
    )
  }
}

let ComposedChild = compose(
      /* --- graphql query */
)(ChildComponent); 



class ParentComponent extends React.Component {
   constructor(props){
     super(props);
   }

   _onClick = ()=>{
      this.childComponent._function1()
      // doesn't show the _function1 and _function2
   }

   render (){
      return (
          <div onClick={this._onClick}>
              <div>Testing</div>
              <ComposedChild ref={(ref) => this.childComponent = ref}/>    
          </div>        
     )
  }
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400