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

174
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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