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

110
Visualizações
React onclick handler for checkbox group

I am using reactjs and I have the following simulation code that is simplify to give better understanding of my question:

     <span onClick={selectHandler}>Select Group 1</span>
    <ul>
      <li>
        <input type="checkbox" id="kw1" name="Group1[]" value="kw1" />
      </li>
      <li>
        <input type="checkbox" id="kw2" name="Group1[]" value="kw2" />
      </li>
      <li>
        <input type="checkbox" id="kw3" name="Group1[]" value="kw3" />
      </li>
    </ul>
    <span onClick={selectHandler}>Select Group 2</span>
    <ul>
      <li>
        <input type="checkbox" id="tr1" name="Group2[]" value="tr1" />
      </li>
      <li>
        <input type="checkbox" id="tr2" name="Group2[]" value="tr2" />
      </li>
      <li>
        <input type="checkbox" id="tr3" name="Group2[]" value="tr3" />
      </li>
    </ul>

My question is how do I write the selectHandler function to select all the checkbox according to Group. Example if user click on Group 1 all the checkboxes kw1, kw2 and kw3 checkboxes will be selected. And when user click on Group 2 all the checkboxes tr1, tr2 and tr3 checkboxes will be selected. When they clicked the Group 1 or Group 2 again, the checkboxes will be deselected according to Group respectively

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There is a simple package that solves this problem grouped-checkboxes.

In your case the render function will look like this:

<CheckboxGroup>
  Select All: <AllCheckerCheckbox /><br/>
  <Checkbox id="option-0" /><br/>
  <Checkbox id="option-1" /><br/>
  <Checkbox id="option-2" /><br/>
</CheckboxGroup>
about 4 years ago · Juan Pablo Isaza Relatório

0

I'd say you'll need to attach a checked prop to your inputs so you can hold the state separately to the ui elements. That way you can programmatically set their state in a separate function.

EDIT:

Ok I've brought this into stackblitz seems I had some spelling mistakes: https://stackblitz.com/edit/react-vcqqif?file=src/App.js

const CheckBoxGroup = () => {
  const [checked, setChecked] = React.useState({
    tr1: false,
    tr2: false,
    tr3: false,
  });

  function handleSelectAll() {
    setChecked((prevState) => {
      /**
       * The following converts the boolen values into an array of primitive
       * types and checks the length against the selected. If all selected then
       * deselect, otherwise select all.
       */
      const stateValues = Object.values(prevState);

      const fullLength = stateValues.length;
      const selectedLength = stateValues.filter(
        (selectedState) => selectedState
      ).length;

      if (fullLength === selectedLength) {
        return {
          tr1: false,
          tr2: false,
          tr3: false,
        };
      }

      return {
        tr1: true,
        tr2: true,
        tr3: true,
      };
    });
  }
  function handleClick(id) {
    setChecked((prevState) => ({
      ...prevState,
      [id]: !prevState[id],
    }));
  }

  return (
    <>
      <button onClick={handleSelectAll}>Select Group 2</button>
      <ul>
        <li>
          <input
            type="checkbox"
            id="tr1"
            name="Group2[]"
            value="tr1"
            checked={checked.tr1}
            onClick={() => handleClick('tr1')}
          />
        </li>
        <li>
          <input
            type="checkbox"
            id="tr2"
            name="Group2[]"
            value="tr2"
            checked={checked.tr2}
            onClick={() => handleClick('tr2')}
          />
        </li>
        <li>
          <input
            type="checkbox"
            id="tr3"
            name="Group2[]"
            value="tr3"
            checked={checked.tr3}
            onClick={() => handleClick('tr3')}
          />
        </li>
      </ul>
    </>
  );
};
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