I have created a textual switch button using HTML and CSS.
I am using that in a React app and I want to detect the selected option whenever it changes. for e.g. if OR
is selected, it should be stored in selectedOption
state and if AND
is selected, that should be stored.
I have made a code sandbox with the demo (https://codesandbox.io/s/stupefied-snyder-lo530)
Can anyone please help me with this?
Thanks
CodePudding user response:
set the state on click, by adding this:
onClick={(e) =>{
selectedOption==="OR" ? setSelectedOption("AND") : setSelectedOption("OR"),
console.log(selectedOption);
}}
CodePudding user response:
As pointed out by @pilchard in comment, e.target.checked
can be used to detect true/false
and then based on that selectedOption
can be set.
onClick={e => {
const currentVal = (e.target as HTMLInputElement).checked;
setSelectedOption(currentVal ? 'AND' : 'OR');
}}