Miha Šušteršič
Miha Šušteršič

Reputation: 10042

ReactJS onClick arguments not getting passed to parent component

I have a component with an injected Mobx store that has the following method:

constructor(props) {
  super(props)

  this.state = {
    propertyChangeNotifications: true,
    smsNotifications: false
  }
}

updateNotifications = (type, value) => {
  this.props.uiStore.updateProfile(type, value)
}

I am passing this method as a prop to a child component:

<ProfileDetails {...this.props.uiStore.profile} updateNotifications={()=> this.updateNotifications()} />

The child component has another method:

constructor(props) {
  super(props)

  // Get profile data from props
  const {
    propertyChangeNotifications,
    smsNotifications,
    person: {
      fiscalId,
      residentialAddress,
      name,
      lastName,
      phoneNumber,
      type,
      email
    }
  } = props

  // Set state according to props
  this.state = {
    name: name,
    lastName: lastName,
    fiscalId: fiscalId,
    residentialAddress: residentialAddress,
    phoneNumber: phoneNumber,
    type: type,
    email: email,
    propertyChangeNotifications: propertyChangeNotifications,
    smsNotifications: smsNotifications
  }
}

handleCheckbox = (type) => {
  this.props.updateNotifications(type, !this.state[type])
  this.setState({
    [type]: !this.state[type]
  })
}

That I am passing to a semantic UI checkbox component:

<Checkbox toggle label="Notify via SMS " checked={smsNotifications} onChange={()=> this.handleCheckbox('smsNotifications')} />

Now what happens is that the Checkbox method (this.handleCheckbox) gets called with the correct argument. Then the this.props.updateNotifications method gets called with the correct arguments as well, but the function in the parent component (updateNotifications), gets called with undefined, undefined.

What am I doing wrong?

Upvotes: 1

Views: 43

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104369

Issue is, at all the places you are binding the method twice, one by using

this.updateNotifications={() => this.updateNotifications()} //here you are calling the function with no parameter.

And one by:

updateNotifications = () => 

Just remove the first way from all the places, it will work.

Simply use:

this.updateNotifications={this.updateNotifications}

and define the function by using arrow function:

updateNotifications = () => 

Upvotes: 1

Lojka
Lojka

Reputation: 167

I think you should pass the function itself, not "invoke the function". Delete () here.

<ProfileDetails
    {...this.props.uiStore.profile}
    updateNotifications={this.updateNotifications}
/>

Upvotes: 1

Related Questions