vendredi 11 mars 2022

antd disable all other Checkboxes when single selected

I was trying to use antd Checkboxes for single selection, but there are no docs about how to disable other checkboxes when single selected. There is "disabled" boolean option which should be true for all checkboxes except selected.

Is that possible with react.jsx?

const [checkList, setCheckList] = useState(array)
const [disable, setDisable] = useState(false)

{checkList.map((item) => (
<CheckBox onChange=(e => e.target.checked ? setDisable(true) : setDisable(false)) disabled={disable}>{item}</CheckBox>))

That what I did, but it disables all of the checkboxes.

UPD: Here is working option, but it doesn't look good. Are there any way to do it better?

const [one, setOne] = useState(false);
  const [two, setTwo] = useState(false);
  const [three, setThree] = useState(false);

<Checkbox
                    onChange={e => {
                      if (e.target.checked) {
                        setTwo(true);
                        setThree(true);
                      } else {
                        setTwo(false);
                        setThree(false);
                      }
                    }}
                    disabled={one}
                  >
                    1
                  </Checkbox>
                  <Checkbox
                    className="ml-0"
                    onChange={e => {
                      if (e.target.checked) {
                        setOne(true);
                        setThree(true);
                      } else {
                        setOne(false);
                        setThree(false);
                      }
                    }}
                    disabled={two}
                  >
                    2
                  </Checkbox>
                  <Checkbox
                    className="ml-0"
                    onChange={e => {
                      if (e.target.checked) {
                        setOne(true);
                        setTwo(true);
                      } else {
                        setOne(false);
                        setTwo(false);
                      }
                    }}
                    disabled={three}
                  >
                    3
                  </Checkbox>



Aucun commentaire:

Enregistrer un commentaire