I have a React app with some check boxes that were mapped out that don't check anymore when the onChange handler function sets a state. However, the checkboxes do work when I am not setting a state without arrays e.g. setState("it works"). But, they don't work when I am setting a state with arrays e.g. setState([...array, value]) and instead remain unchecked. The console.log for e.target.checked remains true and visually is unchecked when I click the checkbox/trigger the onChange handler function. The checkbox works when I don't setState at all. The following is my code snippet, I don't think I am understanding why this is happening.
export default function ReserveModal({ className, openModal }) {
const [roomsData, setRoomsData] = useState([]);
const [selectedRooms, setSelectedRooms] = useState([]);}
const handleSelect = (e) => {
const checked = e.target.checked;
const value = e.target.value;
setSelectedRooms(
checked
? [...selectedRooms, value]
: selectedRooms.filter((item) => item !== value)
);
};
return (
<div className={styles.roomNumbers}>
{roomsData.map((roomNumber) => {
return (
<div key={uuidv4()} className={styles.rooms}>
<label htmlFor="roomNumber">{roomNumber.number}</label>
<input value={roomNumber.number} name="roomNumber" id="roomNumber" type="checkbox" onClick={handleSelect} />
</div>
);
})}
</div>
);
}
e.target.valueto be? Did you mean to usee.target.name?keys. The keys are used internally by react for optimization. You will get unexpected results if you use random keys like that and then update your array. You are supposed to build theidfrom unique data in the array element.checkedattribute of the input. See developer.mozilla.org/en-US/docs/Web/HTML/Element/input/…