简体   繁体   中英

How to disable checkbox in Component based on certain condition in React?

In a React project I've certain records fetched from API. All the records have their respective checkboxes. I want to disable certain checkboxes based on specific condition. Consider following code for better clarity.

const data = [
    { testId: 123, dataId: "44", cycleId: "5050", valid: "N" },
    { testId: 323, dataId: "54", cycleId: "6660", valid: "N" },
    { testId: 444, dataId: "44", cycleId: "4340", valid: "Y" },
    { testId: 134, dataId: "40", cycleId: "5150", valid: "N" },
    { testId: 222, dataId: "42", cycleId: "5050", valid: "Y" },
    { testId: 552, dataId: "38", cycleId: "3244", valid: "Y" }
  ];

Above is the mock data created for sample use. I'm populating the same in a component as below

function CheckboxComp({ data, handleChange }) {
  return (
    <div>
      {data.map((obj) => {
        const { testId } = obj;
        return (
          <label for={testId}>
            {testId}
            <input
              name={testId}
              type="checkbox"
              value={testId}
              disabled={data.valid == "N" ? true : false}
              onChange={handleChange}
            />
          </label>
        );
      })}
    </div>
  );
}

As you can see, all data is mapped in the component. Here I want to disable all the invalid data flagged as 'N', but, it doesn't work. What could be the best solution to tackle this problem?

Please refer to the codesandbox link: https://codesandbox.io/s/pensive-greider-npfdoz?file=/src/CheckOption.js

Its not data.valid.. its obj.valid in Input field

          <input
              name={testId}
              type="checkbox"
              value={testId}
              disabled={obj.valid == "N" ? true : false}
              onChange={handleChange}
            />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM