0

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>
);
}
6
  • What are you expecting e.target.value to be? Did you mean to use e.target.name? Commented Aug 8, 2022 at 20:14
  • Also a FYI. Don't use UUIDs for 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 the id from unique data in the array element. Commented Aug 8, 2022 at 20:17
  • Hi, thanks for your reply. I just edited the code I put in. I am iterating through an array of objects and expecting e.target.value to return the roomNumber.number value, which it does when I console.log it. So I wanted to set that to an array with useState but the checkbox doesn't work when I do that. Commented Aug 8, 2022 at 20:47
  • How would you suggest to build my key instead of using uuid? I'm relatively new and heard that was one way to build your key. Commented Aug 8, 2022 at 20:47
  • You should probably use the checked attribute of the input. See developer.mozilla.org/en-US/docs/Web/HTML/Element/input/… Commented Aug 8, 2022 at 20:49

1 Answer 1

2

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>
);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This did not work for me and when I console.log e.target.checked it's still always true whenever I click the checkbox. I also get an error from react devtools backend "You provided a checked prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultChecked. Otherwise, set either onChange or readOnly.". So I tried changing onClick to onChange and checked to defaultChecked and I am still getting true in console.log and an unticked checkbox no matter how many times I clicked.
I figured it out after rewriting the code and your solution with the checked attribute fixed it, thanks everyone for your contributions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.