0

I'm trying to add a checkbox in react js but it is not changing its value.

function TestToolbar(args) {
  let overRideFlag=0;
  if (overRideFlag === 0){
    overRideFlag=false;
  }
  else{
    overRideFlag=true;
  }
  const handleOverRideChanges = (overRideFlagParm) => {
    overRideFlag=!overRideFlagParm;
  };
  return (
    <div className="">
  <Col sm={1}>
  <div className="" onClick={() => handleOverRideChanges(!overRideFlag)}>
        <input type="checkbox" id="overRideEnabled" name="override" checked={overRideFlag} onChange={() => handleOverRideChanges(overRideFlag)} />
        <label htmlFor="overrid">Override</label>
  </div>
  </Col>
  <Col sm={9}>
    <AddAnotherComponent disabled={disabled} overRideStatus={overRideFlag} />
}
);
}

The issue is that the value of overRideFlag is always true. it is not changing to false at no time. Another issue is checkbox is not getting checked even though its value is true. Finally am passing the value to another component as a prop but it is not getting change. Could anyone kindly advise how the issue can be resolved.

#UPDATE

When I click the checkbox actually the handleOverRide Changed execute twice

1
  • overRideFlag should be in state of the component to get the things you are expected Commented Jun 26, 2020 at 7:05

1 Answer 1

2

Can you try this ?

import React, { useState } from 'react';

function TestToolbar(args) {
  const [overRideFlag, setOverRideFlag] = useState(false);

  return (
    <div className="">
  <Col sm={1}>
  <div className="">
        <input type="checkbox" id="overRideEnabled" name="override" checked={overRideFlag} onChange={() => setOverRideFlag(!overRideFlag)} />
        <label htmlFor="overrid">Override</label>
  </div>
  </Col>
  <Col sm={9}>
    <AddAnotherComponent disabled={disabled} overRideStatus={overRideFlag} />
}
);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.