Trying to add multiple refs to dynamically generated element in ReactJs

Viewed 17

I am trying to add multiple refs to a set of dynamically generated checkboxes. At this point, the checkboxes work, but when I am trying to change the checked state of a particular checkbox, it seems the last one is the only one to have the ref and the state updates just for that particular checkbox.

So far I have this:

    // Setting 6 as a number of states
    new Array(states.length).fill(false)
  );
  // Adding refs to check values
  const inputsRef = useRef([]);

    const handleStateChecked = (position) => {
    const updateCheckedState = isStateChecked.map((isChecked, index) =>
      index === position ? !isChecked : isChecked
    );
        setStateIsChecked((prevState) => updateCheckedState);
   
  };

  return (
   { ... form ...}
            {/* Generating state checkboxes dynamically */}
            {states.map((state, index) => {
              return (
               {...div with styles}
                  <input
                    type="checkbox"
                    checked={isStateChecked[index]}
                    onChange={ () => handleStateChecked(index)}
                    value={state}
                    ref={inputsRef}
                  />
                  {state}
                </div>
              );
            })}
          </div>
        </div>

Could someone guide me in the right direction? Thanks!
0 Answers
Related