I have two checkboxes, if one of them is checked (true) the other one should be unchecked(false).
Code:
export default function App() {
const [input, setInput] = useState({
Checked: {
Score: 1,
Selected: true
},
Unchecked: {
Score: 0,
Selected: false
}
});
const handleChecked = (e) => {
if (input.Unchecked.Selected) {
setInput({
...input,
Checked: {
...input.Checked,
Selected: false
}
});
} else {
setInput({
...input,
Checked: {
...input.Checked,
Selected: e.target.checked
}
});
}
};
const handleUnchecked = (e) => {
if (input.Checked.Selected) {
setInput({
...input,
Unchecked: {
...input.Unchecked,
Selected: false
}
});
} else {
setInput({
...input,
Unchecked: {
...input.Unchecked,
Selected: e.target.checked
}
});
}
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Space>
<Checkbox
checked={input.Checked.Selected}
onChange={(e) => handleChecked}
>
Checked
</Checkbox>
<Checkbox
checked={input.Unchecked.Selected}
onChange={(e) => handleUnchecked}
>
Unchecked
</Checkbox>
</Space>
</div>
);
}
Codesandbox link: https://codesandbox.io/s/patient-pond-zx3vug?file=/src/App.js
The code doesn't change the state onclick. If suppose the first checkbox (Checked) is true then the second checkbox should be false. Incase, the user clicks on the second checkbox, the second checkbox should be true and should make the first checkbox false. (i.e) both of the checkboxes can't be true. But both the checkboxes can be false.