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?

2
  • hmm. weird. Your code snippet seems correct. Commented Nov 23, 2017 at 9: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); Commented Nov 23, 2017 at 9:30

1 Answer 1

0

try adding refs

class Parent extends Component {
hoverOn(){
    this.refs._Child.someMethod(10);
}}
Sign up to request clarification or add additional context in comments.

3 Comments

The OP has added a ref using the callback method which is what is recommended in the docs
OP has used a better method than what you've suggested.
Oh sorry guys . I didnt see that he used a callback method

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.