Home > Mobile >  Why does react input checkbox not check when onChange handler is setting state?
Why does react input checkbox not check when onChange handler is setting state?

Time:08-09

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>
);
}

CodePudding user response:

You don't actually set the checked attribute of the input. I think something like this should work:

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 checked={selectedRooms.includes(roomNumber.number)} value={roomNumber.number} name="roomNumber" id="roomNumber" type="checkbox" onClick={handleSelect} />
              </div>
            );
          })}
       </div>
);
}
  • Related