Issue with this.setState() not updating value despite not being related to asynchronous updates

Just a quick note, this specific question does not involve any asynchronous update problem (at least, as far as I can tell).

I currently have a class component with the following code snippet (simplified for clarity on the main issue):

  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("----")
        
     });
     } 
 }

Within the render return section, I've included the following:

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

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

The output recorded in Chrome Developer Tools displays how the "checked" status changes accordingly when selecting and deselecting checkboxes. Nevertheless, the state of "selected" (should be "aSelected") remains unaltered and retains its initial false value. Any insights into why "selected" (should be "aSelected") is not updating?

Edit: The task I'm aiming to achieve involves two checkbox items where the user can only choose ONE or none at all. If one is selected, the other should be disabled.

https://i.stack.imgur.com/51WU2.png

Answer №1

Whenever you update the state by calling setState in React, the component is re-rendered and the checkbox goes back to its default unchecked state.

To effectively manage the checkbox state, make sure to use the current state. Your JSX structure should resemble this:

<input
   type="checkbox"
   checked={this.state.aSelected}
   onChange={this.handleCheckboxChange}
/>

In React's terminology, this falls under a "controlled component" category as React handles all changes to the input state. For further information, refer to the documentation here: https://reactjs.org/docs/forms.html#controlled-components or https://reactjs.org/docs/uncontrolled-components.html

Revision for Question Adjustments: Ensure that in your render function, you are using this.state.aSlected. Additionally, do not forget to include the checked={this.state.aChecked} attribute, or else the checkbox will remain unchecked upon the next rendering. For example:

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

Revise with Functional Example Here is an interactive CodeSandbox demonstration showcasing how checking one checkbox disables the other:

class CheckboxComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      aSelected: false,
      bSelected: false
    };
  }

  handleCheckbox = (event) => {
    if (event.target.name === "boxA") {
      this.setState({ aSelected: event.target.checked });
    } else if (event.target.name === "boxB") {
      this.setState({ bSelected: event.target.checked });
    }
  };

  render() {
    let aDisabled = this.state.bSelected && !this.state.aSelected;
    let bDisabled = this.state.aSelected && !this.state.bSelected;

    return (
      <div>
        <label>
          <input
            type="checkbox"
            name="boxA"
            checked={this.state.aSelected}
            onChange={this.handleCheckbox}
            disabled={aDisabled}
          />
          Checkbox A
        </label>
        <br />
        <br />
        <label>
          <input
            type="checkbox"
            name="boxB"
            checked={this.state.bSelected}
            onChange={this.handleCheckbox}
            disabled={bDisabled}
          />
          Checkbox B
        </label>
      </div>
    );
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clearing input fields after submitting a form in React can be achieved by setting the

As I work on completing my portfolio, I've reached the final page which is the contact form. Most of it is done and set up with emailjs to receive messages as expected. The issue I'm facing now is that upon submitting the form, I am unable to cl ...

When attempting to append a script element and the operation fails due to lack of authorization, which error is typically thrown

I am trying to handle a particular failure in this JavaScript code: var script = $wnd.document.createElement('script'); script.setAttribute('src', url); script.setAttribute('type', 'text/javascript'); When the URL ...

Steps to redirect to a webpage by clicking on an image without relying on anchor tags

Is it possible to redirect to a new webpage without using an anchor tag when someone clicks on an image? Below is my code for the image. <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/368px-Google_2015_l ...

Struggling to Display/Retrieve a MongoDB Entry by its Unique Identifier in React

Despite my best efforts and a few minor setbacks, I am still struggling to retrieve an object by its ID in my React frontend. The issue arises when trying to access properties of the object in my Post Component. Even though the data seems available based o ...

Is there a faster way to create a typescript constructor that uses named parameters?

import { Model } from "../../../lib/db/Model"; export enum EUserRole { admin, teacher, user, } export class UserModel extends Model { name: string; phoneNo: number; role: EUserRole; createdAt: Date; constructor({ name, p ...

Declare React component as a variable

I'm facing a simple issue that I need to solve. After creating a React app using npx create-react-app, I designed a Map component which I integrated into my view with the following code: class App extends Component { render() { return ( ...

Leveraging the Power of jsPDF in Your Google Apps Scripts

Is it feasible to integrate jsPDF into a Google Apps Script project? I am attempting to create documents using templated HTML, but certain CSS styles like background-color do not translate to PDF when using the getAs() function. Given the limitations of ...

Managing state on the login page functions properly, although there is a minor inconvenience of having to click the login button twice after entering the username and password

In Login.tsx, I store user/pass info in a useState called login and pass it up to App.tsx. I then store the access property from login useState to access useState inside App.tsx. While this does technically work, there is an issue where it seems to be one ...

Add a click function to an element in a grid when it is databound

In my TypeCtrl ES6 class angular controller, I am using a kendo datagrid directive with a template for grid config options. Within the grid template, I need to call a method from the TypeCtrl class when a span within the row is clicked. However, the functi ...

Confusing postback phenomena in ASP.NET web forms

I have developed a small script that successfully maintains the focused element during an async postback. However, I encountered an issue when tabbing through controls generated inside an asp:Repeater, where a full postback is unexpectedly triggered. Below ...

Unable to retrieve the value of a key from a node object

I'm baffled by how this is even possible For example, when I execute this code: console.error(order.Items[i]); The output is: { ItemURL: '', IsBundle: false, GiftTaxPrice: '0', GiftPrice: '0', GiftNotes: null ...

Using Formik with MUI Multiple Select

Exploring the world of MUI and Formik, I encountered a challenge with creating a multiple Select in my form. It's my first time working with these tools, so I have a question regarding the implementation. Here's what I've tried based on the ...

Tips for transferring information from a child component to its parent using a click event in the parent component

My React application is designed to generate quizzes. The main component, <CreateQuiz/>, contains a child component called <QuestionForm/>. Additionally, within the <CreateQuiz/> component, there is a button labeled "Add Question" which a ...

The error message "window is not defined" occurs when the external file 'signalr.min.js' is included

Updates OpenTest --version 1.2.2 ChromeDriver 85.0.4183.87 Whenever I attempt to add the necessary external javascript files, it results in the following errors: Caused by: java.lang.RuntimeException: Failed to evaluate JavaScript code at line number 1. ...

Quickest method for skimming through an extremely lengthy document beginning at any specified line X

In my current project, there is a text file that is written to by a python program and read by another program to display on a web browser. JavaScript handles the reading process at the moment, but I am considering moving this functionality to python. The ...

Custom sorting in JavaScript

I have a specialized sorting method that is defined as follows sortArrayBy: function(a, b, sortKey) { if (a[sortKey] < b[sortKey]) return -1; if (a[sortKey] > b[sortKey]) return 1; return 0; }, I am looking to enhance it ...

Is it possible to adjust table rows to match the height of the tallest row in the table?

I've been attempting to ensure that all table rows have the same height as the tallest element, without using a fixed value. Setting the height to auto results in each row having different heights, and specifying a fixed value is not ideal because the ...

What is the best way to ensure the remaining PHP script is executed after using json_encode()?

My current project involves creating a form with four input fields: name, email, phone, and message. To handle the submission process, I am utilizing JavaScript in conjunction with Ajax to send the user inputs to a PHP file for validation and mailing using ...

Retrieving and assigning data values within an Angular JS service

Here is the service I created to fetch user details: angular.module('app') .factory('userDetailService', function($http) { var userData = {}; function getUserDetails(userId) { if (userId) { return $http.get ...

Utilizing jQuery to extract the id and update its content

One of my tasks involves working with a table generated by PHP and incorporating a modal that allows users to change the text produced by the variable $l_id. I have a link with a class "eloc" that triggers the display of the modal div section. By intercept ...