shashi
shashi

Reputation: 4696

Calling a method on Parent Component from Child Component

The project I am working on has a NotificationHeader component which has the infra for showing notifications. Specifically, it has a method

addNotification(msg,type)   {
  console.log('addNotification.this:%O',this);
  // rest of the method to show notification. 
}

The rest of the components on the page are children to this NotificationHeader component. I am passing the addNotification method down to the children as props, so that I can call it from them.

The issue I am facing is that when I call the addNotification method from the child, the reference to this inside the addNotification is not pointing to the NotificationHeader component, but to addNotification.

Image of the error in js console

The other examples that I have seen for calling a parent component method from child do not seem to face this issue.

I must mention that since the project uses React router, to pass the addNotification method down to the children I am using React.cloneElement as follows:

{React.cloneElement(this.props.children, {
    addNotification: this.addNotification,
})}

How can I get this to refer to the NotificationHeader component?

Upvotes: 0

Views: 290

Answers (1)

Bartek Fryzowicz
Bartek Fryzowicz

Reputation: 6684

I think that you should pass down addNotification method with bound context. You can use bind to do this:

<SomeChildComponent addNotification={this.addNotification.bind(this)} />

or if you clone component as you mentioned:

{React.cloneElement(this.props.children, {
    addNotification: this.addNotification.bind(this)
})}

Upvotes: 1

Related Questions