unable to check the checkedbox


Direct DOM mutation is an anti-pattern in react (it is outside react so react can’t know to rerender).

The handler also doesn’t access the checked property of the onChange event.

const { checked } = event; // <-- should be event.target


Use react state to maintain the checked status in component state.

Move the departments data into component state.

const [departments, setDepartments] = useState(departmentsData);

Move the handleJobTitle handler into the component. I suggest using a curried function that accepts the sector id, department name, and the job id, you’ll need these to “trace” the path to the correct nested object. You don’t need to worry about getting the checked property from event.target as you can simply invert a checked value in state via the JobTitleID key value.

The idea here is to shallow copy any nested state, into new object references for react, that is being updated.

const handleJobTitle = (sectorId, deptName, JobTitleID) => () => {
  setDepartments((data) =>
    data.map((sector) =>
      sector.sectorId === sectorId
        ? {
            departments: sector.departments.map((dept) =>
              dept.deptName === deptName
                ? {
                    jobTitles: dept.jobTitles.map((job) =>
                      job.JobTitleID === JobTitleID
                        ? {
                            [JobTitleID]: !job[JobTitleID]
                        : job
                : dept
        : sector

Now simply attach the handleJobTitle to the input’s onChange handler.

  onChange={handleJobTitle( // <-- pass the required values

Edit unable-to-uncheck-the-checkbox

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top