vendredi 8 mai 2020

Checkbox not updating in react table

I've been learning and working on react lately. While creating a table using react-table component i've encountered a problem whit a checkbox I added to the headers of the table.

My main problem is that the checkboxes have a weir behaviour and it is not getting checked as it must have.

I've tried to save the items I have checked on an state object using useState hook.

const [selected, setSelected] = useState([]);

Here is the header:

{
     Header: "CheckBox",
     accessor: "",
     Cell: ({ row }) => {
      return(<input 
              type="checkbox"
              checked={!isChecked(row.original)}
              onChange={() => checkBoxHandler(row.original)}/>
      )
     }
}

This is the function checkBoxHandler()

const checkBoxHandler = (row) =>{
        if(!isChecked(row)){
            const arr = [...selected];
            arr.push(row);
            selected(arr); 
        }
        else{
            const arr = [...selected];
            arr.splice(selected.indexOf(row),1);
            setSelected(arr);
        }
    }

And this is the isChecked() function

const isChecked = (row) =>{
        return (selected.includes(row));

    }

I would like to know if my logic has any problem or there is a more efficient way of implementing this




Aucun commentaire:

Enregistrer un commentaire