What should I do if I would like to limit the selected checkboxes to 3, which you cannot select more than 3 checkboxes. By referring this link https://codesandbox.io/s/wild-silence-b8k2j?file=/src/App.js How to add some code to limit the selection here? I am trying to play around this but didn’t figure out
CodePudding user response:
const handleOnChange = (position) => {
const updatedCheckedState = checkedState.map((item, index) =>
index === position ? !item : item
);
// allow only 3 elements
if (updatedCheckedState.filter(v => v).length >= 4) {
return
}
setCheckedState(updatedCheckedState);
const totalPrice = updatedCheckedState.reduce(
(sum, currentState, index) => {
if (currentState === true) {
return sum toppings[index].price;
}
return sum;
},
0
);
setTotal(totalPrice);
};
CodePudding user response:
Try this, you need to check length of selected array and checked status of current input
const handleOnChange = (position, e) => {
if (checkedState.filter((i) => i).length >= 3 && e.target.checked) return;
const updatedCheckedState = checkedState.map((item, index) =>
index === position ? !item : item
);
setCheckedState(updatedCheckedState);
const totalPrice = updatedCheckedState.reduce((sum, currentState, index) => {
if (currentState === true) {
return sum toppings[index].price;
}
return sum;
}, 0);
setTotal(totalPrice);
};
<input
type="checkbox"
id={`custom-checkbox-${index}`}
name={name}
value={name}
checked={checkedState[index]}
onChange={(e) => handleOnChange(index, e)}
/>
CodePudding user response:
Let's start from the state array...
As argument, use a function instead a direct value. It works the same, but it prevents to recreate uselessly an array (then fill it), which will be trashed on every render.
const [checkedState, setCheckedState] = useState(
() => new Array(toppings.length).fill(false)
);
Then, count how many are currently selected:
const selectedCount = checkedState.reduce((sum, currentState, index) => {
if (currentState === true) {
return sum 1;
}
return sum;
}, 0);
Finally, prevent further selections on the checkboxes which are still selectable:
<input
type="checkbox"
id={`custom-checkbox-${index}`}
name={name}
value={name}
checked={checkedState[index]}
onChange={(e) => handleOnChange(index, e)}
disabled={!checkedState[index] && selectedCount >= 3}
/>