Gnanaseelan
Gnanaseelan

Reputation: 404

Disable switch button in React

If I click on the Annual radio button, then switch button (labelled "half day") should be hidden or disabled (only for Annual radio button). How do I do this in React?

<RadioGroup onChange={this.onChange} value={this.state.leavevalue}>
    <Radio value={1}>Casual</Radio>
    <Radio value={2}>Medical</Radio>
    <Radio value={3}>Annual</Radio>
    <Radio value={4}>Lieu</Radio>
    <Radio value={5}>Special</Radio>
    <Radio value={6}>Maternity</Radio>
    <Radio value={7}>Paternity</Radio>
    <Radio value={8}>NoPay</Radio>
</RadioGroup>

This is my switch button code :

<Switch onChange={this.handleHalfDay} checked={this.state.isHalfDay} />

This is my onChange function:

onChange = (e) => {
    this.setState({
        leavevalue: e.target.value,
        isHalfDay: false,
    });
}

My radio buttons and the switch button:

radio buttons and the switch button

Upvotes: 1

Views: 7342

Answers (2)

Tholle
Tholle

Reputation: 112777

You can disable the Switch when your leavevalue state variable is equal to 3.

Example

class App extends React.Component {
  state = {
    leavevalue: 1,
    isHalfDay: true
  };

  handleChange = value => {
    this.setState({ leavevalue: value });
  };

  handleHalfDay = () => {
    this.setState(previousState => {
      return { isHalfDay: !previousState.isHalfDay };
    });
  };

  render() {
    return (
      <div>
        <RadioGroup
          selectedValue={this.state.leavevalue}
          onChange={this.handleChange}
        >
          <Radio value={1} />Casual
          <Radio value={2} />Medical
          <Radio value={3} />Annual
          <Radio value={4} />Lieu
          <Radio value={5} />Special
          <Radio value={6} />Maternity
          <Radio value={7} />Paternity
          <Radio value={8} />NoPay
        </RadioGroup>
        <Switch
          onChange={this.handleHalfDay}
          checked={this.state.isHalfDay}
          disabled={this.state.leavevalue === 3}
        />
      </div>
    );
  }
}

Upvotes: 4

vijayst
vijayst

Reputation: 21826

A simple conditional statement will do:

onChange = (e) => {
    this.setState({
      leavevalue: e.target.value,
      isHalfDay: false,
      isHalfDayHidden: e.target.value === 3
    });
  }

And another conditional to show or hide the Switch

{!this.state.isHalfDayHidden && (
  <Switch onChange={this.handleHalfDay} checked={this.state.isHalfDay} />
)}

Upvotes: 2

Related Questions