Home > Back-end >  How to handle checkbox action - react native?
How to handle checkbox action - react native?

Time:03-15

I have two function :

    const SelectCheckBox = (obj, isChecked) => {
    
        if (isChecked) {
          result  = parseFloat(obj.value);
        } else {
          result -= parseFloat(obj.value);
        }
    
      };
    
      const SelectAllRadioButton = (objList) => {
        setSelectAll(true);
        result = 0;
    
        for (const property in objList) {
          result  = parseFloat(objList[property].value);
        }
    
      };

    {props.List?.map((item, index) => renderRow(item, index))}

const renderRow = (obj, index) => (
             <Field
              checked={selectAll}
              component={checkboxComponent}
              name={index}
              onChange={(isChecked) => SelectCheckBox({ index, obj }, isChecked)}
            />
)
      

When I click SelectAllRadioButton all checkboxes are checked. When I click SelectCheckBox, checkbox which i clicked should be unchecked. However, I cant do it because of checked={selectAll}. How can i handle this

CodePudding user response:

You need a boolean value for each individual checkbox. You are using the same value for all of them.

You could use an array as a state in which each element represents the check state of the checkbox with the same index.

  const [checks, setChecks] = useState(props.List ? props.List.map(item => false) : [])

     const toggleChecked = (idx) => {
        setChecks(checks.map((item, index) => {
             index === idx ? !item : item
        }))
      };
    
      const SelectAllRadioButton = (objList) => {
        
          setChecks(checks.map((item) => true))
      };

    {props.List?.map((item, index) => renderRow(item, index))}

     const renderRow = (obj, index) => (
             <Field
              checked={checks[index]}
              component={checkboxComponent}
              name={index}
              onChange={(isChecked) => toggleChecked(index)}
      />)
  • Related