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
Select only ONE or NONE of the checkbox inputs

My goal is to have two checkbox items, where the user can only select ONE or select NONE. While one is selected, the other should be disabled. I have this so far, but it is not working as I expected.

If there is a better way to this overall, please let me know!!

I have a class component with the following content:

  constructor(props) {
     super(props);
     this.state = {
       aSelected: false,
       bSelected: false
     }
  }

 handleCheckboxChange = (e) => {   
     const { checked, value } = e.target;
    
     console.log( 'checked: ', checked );

     if(value=="a") {
        this.setState( {aSelected: checked}, () =>  {
        console.log('aSelected: ', this.state.aSelected);
        console.log("---")
     });
     }

     if(value=="b") {
        this.setState( {bSelected: checked}, () =>  {
        // console.log('bSelected: ', this.state.bSelected);
        // console.log("---")
     });
     } 
 }

Somewhere inside the render return, I have this:

<input>
   type="checkbox"
   value="a"
   onChange={this.handleCheckboxChange}
   disabled={ (this.state.aSelected || (!this.state.aSelected && !this.state.bSelected) ) ? false : true} 
</input>

<input>
   type="checkbox"
   value="b"
   onChange={this.handleCheckboxChange}
   disabled={ (this.state.bSelected || (!this.state.aSelected && !this.state.bSelected) ) ? false : true}
</input>

Problems I'm having:

  1. The disabled behavior is NOT matching up with how I detailed it in the first line.
  2. this.state.aSelected and this.state.bSelected always log false no matter how many times I select and unselect the checkbox. The checked value is correctly toggled, though. (Below is the ouput for toggling the "a checkbox"):

enter image description here

about 4 years ago · Juan Pablo Isaza
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