Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
Trigger onChange function even if an option is already chosen in react

I'm looking how to trigger onChange function when an option is already selected and clicked by the user to deselect it, it's like multiselect. you can select an option and deselect it by clicking on it a second time. this is what i've already tried. everything is working when there is more than 1 option selected, but not when there is only one option selected.

const handleChangeGroup = (selectedItems) => {
    const groups = [];
    for (let i = 0; i < selectedItems.length; i++) {
      if (groupArray.includes(selectedItems[i].value)) {
        if (groupArray.length === 0) {
          setGroupArray([]);
        } else {
          var newArray = groupArray.filter(
            (value) => value != selectedItems[i].value
          );
          setGroupArray(newArray);
        }
      } else {
        groups.push(selectedItems[i].value);
        setGroupArray(groupArray.concat(groups));
      }
    }
  };


<select
            multiple={true}
            value={groupArray}
            onChange={(event) =>
              handleChangeGroup(event.target.selectedOptions)
            }>
            {data[selectType] !== undefined
              ? Object.keys(data[selectType]).map((group, index) => (
                  <option value={group} key={group}>
                    {group}
                  </option>
                ))
              : null}
          </select>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Executable example:

const Sample = () => {
    const data = ['a', 'b', 'c'];
    const [groupArray, setGroupArray] = React.useState([]);

    const handleChangeGroup = (selectedItem) => {
        if (groupArray.includes(selectedItem)) {
            const tempArray = groupArray.filter(item => item !== selectedItem);
            setGroupArray([...tempArray]);
        } else {
            setGroupArray([...groupArray, selectedItem]);
        }
    };

    return (
        <select
            multiple
            value={groupArray}
            onClick={e => handleChangeGroup(e.target.value)}
        >
            {data.map((group, index) => (
                <option value={group} key={group}>
                    {group}
                </option>
            ))}
        </select>
    );
};

ReactDOM.render(<Sample />, document.querySelector("#app"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="app"></div>

You might want to consider using checkboxes for a more intuitive UI and more concise code.

If you don't want to use checkboxes, you can use this code:

const handleChangeGroup = (selectedItem) => {
    if (groupArray.includes(selectedItem)) {
        const tempArray = groupArray.filter(item => item !== selectedItem);
        setGroupArray([...tempArray]);
    } else {
        setGroupArray([...groupArray, selectedItem]);
    }
};

return (
    <select
        multiple
        value={groupArray}
        onClick={e => handleChangeGroup(e.target.value)}
    >
        {data[selectType] !== undefined
            ? Object.keys(data[selectType]).map((group, index) => (
                <option value={group} key={group}>
                    {group}
                </option>
            ))
            : null}
    </select>
);

The reason onChange won't work is because the default behavior of select is to make the user choose at least one option. Clicking on the last selected option will not deselect anything. So onChange won't fire when you have only one selected item left. You can override this replacing onChange with onClick.

For a simpler example/test, you can try using select without the multiple attribute. Clicking on the currently selected option won't fire any deselect events either.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda