Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda