0

I am trying to access a child method from the parent component. This is how the child code looks like

class child extends Component {

someMethod(v) {
// do something
}

render(){
return(
...
)
}
}

And this is the parent code

class Parent extends Component {
hoverOn(){
this._Child.someMethod(10);  // _Child is undefined here
}

render(){
return(
<div onMouseOver={this.hoverOn.bind(this)}>
<OtherChild ....>
<Child  ref={(Child) => { this._Child = Child; }} />
</div>
)
}
}

On hoverOn() I get an error telling me that _Child is undefined. How can I call someMethod() from the Parent Class?

user567
  • 3,712
  • 9
  • 47
  • 80
  • hmm. weird. Your code snippet seems correct. – Jeff P Chacko Nov 23 '17 at 09:26
  • Two things, your child component class names is `child` whereas it should be `Child`, other thing is that since you have onMouseOver event which may get triggered before the component is mounted and hence you can get an error so add a conditional check like `this._Child && this._Child.someMethod(10);` – Shubham Khatri Nov 23 '17 at 09:30

1 Answers1

0

try adding refs

class Parent extends Component {
hoverOn(){
    this.refs._Child.someMethod(10);
}}
Jeffin
  • 1,099
  • 12
  • 23