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

175
Visualizações
how will I change the state of a checkbox that is dependent on another checkbox

I have two checkboxes, if one of them is checked (true) the other one should be unchecked(false).

Code:

export default function App() {
  const [input, setInput] = useState({
    Checked: {
      Score: 1,
      Selected: true
    },
    Unchecked: {
      Score: 0,
      Selected: false
    }
  });
  const handleChecked = (e) => {
    if (input.Unchecked.Selected) {
      setInput({
        ...input,
        Checked: {
          ...input.Checked,
          Selected: false
        }
      });
    } else {
      setInput({
        ...input,
        Checked: {
          ...input.Checked,
          Selected: e.target.checked
        }
      });
    }
  };
  const handleUnchecked = (e) => {
    if (input.Checked.Selected) {
      setInput({
        ...input,
        Unchecked: {
          ...input.Unchecked,
          Selected: false
        }
      });
    } else {
      setInput({
        ...input,
        Unchecked: {
          ...input.Unchecked,
          Selected: e.target.checked
        }
      });
    }
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Space>
        <Checkbox
          checked={input.Checked.Selected}
          onChange={(e) => handleChecked}
        >
          Checked
        </Checkbox>
        <Checkbox
          checked={input.Unchecked.Selected}
          onChange={(e) => handleUnchecked}
        >
          Unchecked
        </Checkbox>
      </Space>
    </div>
  );
}

Codesandbox link: https://codesandbox.io/s/patient-pond-zx3vug?file=/src/App.js

The code doesn't change the state onclick. If suppose the first checkbox (Checked) is true then the second checkbox should be false. Incase, the user clicks on the second checkbox, the second checkbox should be true and should make the first checkbox false. (i.e) both of the checkboxes can't be true. But both the checkboxes can be false.

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

0

You don't need 2 functions to handle the same. You can toggle the value when it's clicked. check here

Issue with your code: You are not calling function

onChange={handleChecked}

Better Solution:

export default function App() {
  const [input, setInput] = useState({
    Checked: {
      Score: 1,
      Selected: true
    },
    Unchecked: {
      Score: 0,
      Selected: false
    }
  });
  const handleChecked = (e) => {
    setInput((input) => ({
      ...input,
      Checked: {
        ...input.Checked,
        Selected: !input.Checked.Selected
      },
      Unchecked: {
        ...input.Unchecked,
        Selected: !input.Unchecked.Selected
      }
    }));
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Space>
        <Checkbox checked={input.Checked.Selected} onChange={handleChecked}>
          Checked
        </Checkbox>
        <Checkbox checked={input.Unchecked.Selected} onChange={handleChecked}>
          Unchecked
        </Checkbox>
      </Space>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

The way you are defining state for checkboxes can be simplified. For 2 checkboxes it's probably ok, however if you need to construct checkboxes from json array then you will run into problem.

So I will define the state like this, array of objects consisting all metadata regarding each checkbox control.

 const [input, setInput] = useState([
    { name: "chkbox1", Score: 1, Selected: true },
    { name: "chkbox2", Score: 0, Selected: false }
  ]);

so in jsx you have to adopt the change accordingly, currently for your example it would be like this, however again this could be in .map function as iterable controls.

<Checkbox
          name="chkbox1"
          checked={input[0].Selected}
          onChange={handleChecked}
        >
          Checked
</Checkbox>
<Checkbox
          name="chkbox2"
          checked={input[1].Selected}
          onChange={handleChecked}
        >
          Unchecked
</Checkbox> 

Finally in handleChecked event, you can find other checkbox which is not checked and toggle that accordingly. You can do it even without name, but just by passing index.

const handleChecked = (e) => {    
    let temp = [...input];
    let otherCheckboxIndex = temp.findIndex((obj => obj.name !== e.target.name));
    let thisCheckboxIndex = temp.findIndex((obj => obj.name === e.target.name));       
    temp[otherCheckboxIndex].Selected = !e.target.checked;
    temp[thisCheckboxIndex].Selected = e.target.checked;
    setInput(temp);
};

See here codesandbox.

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