Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox always passing false even if checked in React

I have a checkbox and when it's checked/unchecked, it writes true or false in the console, however, when I try and save the value, it's always passing false.

html:

<input type="checkbox" 
       name="Status"
       value="Status"
       onChange={(e) => {carStatus(e)}) />
const CarState = {
      carId: 0,
      Make: "",
      Model: ""
      Active: ""   //this is a bit in the DB
}

const [carMake, setCarMake] = useState(CarState);
const [carModel, setCarModel] = useState(CarState);
const [carActive, setActive] = useState(CarState);

const carStatus = (e) => {
   const status = e.target.checked;
   if(status)
   {
      console.log("checked " + status);
      setCarActive({ ...carActive, status});
   }
   else
   {  
      console.log("checked" + status);
      setCarActive({ ...carActive, status});
   }

const saveCar = () => {
       var data = {
          make: carMake.CarMake,
          model: carModel.Model,
          active: saleActive.Active  //always false even if checkbox is checked
      };
  
     //passes data to the API

}

Is there a better way to do this or a different way? I can see true/false in F12 if the checkbox is checked or not, however, just passes false when I click the save button [saveCar function]

like image 902
JustWantsToCode Avatar asked Mar 17 '26 04:03

JustWantsToCode


1 Answers

You are not updating the nested Active state, you are adding a status property and not referencing it. Use the checked value and update the Active property in state.

const [carActive, setCarActive] = useState(CarState);

...

const carStatus = (e) => {
  const { checked } = e.target;

  console.log("checked " + checked);

  setCarActive(carActive => ({
    ...carActive,    // <-- shallow copy previous state
    Active: checked, // <-- set new Active checked value
  }));
}

In the input you should reference the state. Use the checked prop/attribute/

<input
  type="checkbox" 
  name="Status"
  value="Status"
  checked={carActive.Active} // <-- set the checked prop of input
  onChange={carStatus}
/>

In saveCar reference the correct state being updated. Ensure all the properties being accessed match the carState properties.

const saveCar = () => {
  var data = {
    make: carMake.Make,
    model: carModel.Model,
    active: carActive.Active 
  };
  
  //passes data to the API

}

Working Demo

Edit checkbox-always-passing-false-even-if-checked-in-react

like image 86
Drew Reese Avatar answered Mar 20 '26 04:03

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!