D
D
DanceMonkeyTime2020-09-10 11:14:05
JavaScript
DanceMonkeyTime, 2020-09-10 11:14:05

How to properly implement a function to change an array?

Hello.

I have a component that has props multiSelection: true | false;
. I have an array selected: []and checkboxes that have a state. checked: true | false.

If I have , then several values ​​​​can be written to the array if we delete the element. If I have , then only one value should be written to the array and removed too. I'm trying to come up with something sensible, but something doesn't work:multiSelection = true и checked = truechecked =. false

multiSelection = false и checked = true

const [selected, toggleSelected] = useState([]);

const setSelected = (option, checked) => {
    const selectedValues = [...selected];
    if (multiSelection) {
      if (checked) {
        toggleSelected([...selectedValues, option]);
      } else {
        const filteredArray = selectedValues.filter(
          (item) => item.key !== option.key
        );
        toggleSelected(filteredArray);
      }
    } else {
      if (checked) {
        toggleSelected([option]);
      } else {
        selectedValues.pop();
        toggleSelected(selectedValues);
      }
    }
  };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-09-10
@DanceMonkeyTime

const [selected, setSelected] = useState([]);

const toggleSelected = (option, checked) => {
    if (multiSelection) {
        setSelected(selected => checked
            ? [...selected, option.key]
            : selected.filter(entry => entry !== option.key)
        );
    } else {
        setSelected(checked
            ? [option.key]
            : []
        );
    }
};

I think that it is better to store marked elements not as objects, but as strings. Also, your variables were named the other way around, this introduced a little confusion - toggleSelectedit did not have switching logic, although by name it should have. The same thing happened with setSelected. Demo .
By the way, I think you can think about UX, because if you can select only 1 checkbox, then can radio do it? If so, it will be possible to remove this logic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question