unable to check the checkedbox

Issue(s)

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

Solution

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
        ? {
            ...sector,
            departments: sector.departments.map((dept) =>
              dept.deptName === deptName
                ? {
                    ...dept,
                    jobTitles: dept.jobTitles.map((job) =>
                      job.JobTitleID === JobTitleID
                        ? {
                            ...job,
                            [JobTitleID]: !job[JobTitleID]
                          }
                        : job
                    )
                  }
                : dept
            )
          }
        : sector
    )
  );
};

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

<input
  type="checkbox"
  id={job.JobTitleID}
  onChange={handleJobTitle( // <-- pass the required values
    levelOne.sectorId,
    levelTwo.deptName,
    job.JobTitleID
  )}
  name={job.JobName}
  checked={job[job.JobTitleID]}
/>

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