Disable switch button in React


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





There's no such switch in your code.
– apokryfos
Jul 1 at 7:43





RadioGroup - What library is it part of?
– vijayst
Jul 1 at 8:15




2 Answers
2



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


Switch


leavevalue


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>
);
}
}





tholle thank you sir code is working
– Gnanaseelan
Jul 1 at 10:52





@Gnanaseelan You're welcome. Great!
– Tholle
Jul 1 at 10:53



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} />
)}





vijayst sir ..not working
– Gnanaseelan
Jul 1 at 8:58





Maybe, you can try e.target.value == 4. value might be a string.
– vijayst
Jul 1 at 9:32


e.target.value == 4






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API