Answer the question
In order to leave comments, you need to log in
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 = true
checked =. 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
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]
: []
);
}
};
toggleSelected
it did not have switching logic, although by name it should have. The same thing happened with setSelected
. Demo . Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question