Nothing here
Nothing here

Reputation: 2373

How to combine two functions but change two separate states individually

I have two items which have separate states and a function which toggles their state. How can I change the state of each item using only one function?

The items:

<Form.Check
    type="switch"
    id="smsNotificationSwitch"
    label="SMS Notifications"
    checked={this.state.smsNotifications}
    onChange={this.toggleSMSSwitch}
/>
<Form.Check
    type="switch"
    label="Email Notifications"
    id="emailNotificationSwitch"
    checked={this.state.emailNotifications}
    onChange={this.toggleEmailSwitch}
/>

The state:

state = {
    smsNotifications: true,
    emailNotifications: true,
}

the functions I would like to combine:

toggleSMSSwitch = () => {
  this.setState((prevState) => (
      {smsNotifications: !this.state.smsNotifications}));
};
toggleEmailSwitch = () => {
  this.setState((prevState) => (
      {emailNotifications: !this.state.emailNotifications})
  );
};

I am asking to learn more than anything else.

Upvotes: 0

Views: 39

Answers (1)

michael
michael

Reputation: 4173

You can add name attribute as the same as the state variable name. On onChange handler you can get name from the event param.

<Form.Check
    name="smsNotifications"
    type="switch"
    id="smsNotificationSwitch"
    label="SMS Notifications"
    checked={this.state.smsNotifications}
    onChange={this.toggleSwitch}
/>
<Form.Check
    name="emailNotifications"
    type="switch"
    label="Email Notifications"
    id="emailNotificationSwitch"
    checked={this.state.emailNotifications}
    onChange={this.toggleSwitch}
/>
toggleSwitch = event => {
  const { name } = event.target;
  this.setState({ [name]: !this.state[name] });
};

Upvotes: 1

Related Questions