mercredi 1 septembre 2021

How to set a react use state array from onSelectAll checkbox in react bootstrap table

I have a table with multiple rows and each row has a corresponding checkbox. Currently when I check a checkbox I have a use state array that updates with a name from the row. i.e if I have a table with three rows, Bob, Jon, Joe, and each name has a checkbox next to it, upon the checkbox being clicked the name enters into the array.

const handleAdd = (fileRow) => {
        setSelectedFileRows([...selectedFileRows, fileRow]);
    };
    const handleRemove = (fileRow) => {
        const newFiles = selectedFileRows.filter((t) => t !== fileRow);
        setSelectedFileRows(newFiles);
    };
    const selectRow = {
        mode: "checkbox",
        style: { backgroundColor: "#c8e6c9" },
        onSelect: (row, isSelect) => {
            if (isSelect) {;
                handleAdd(row.name);
            } else {
                handleRemove(row.name);
            }
        }

This all works fine and dandy but when I try to populate the array with onSelectAll where one checkbox gets clicked and all the rows are likewise checked off, the array does not populate properly.

onSelectAll: (isSelect, rows) => {
            if (isSelect) {
                rows.forEach((row) => {
                    handleAdd(row.name);
                });
            } else {
                rows.forEach((item) => {
                    handleRemove(item.name);
                });
            }
        }

I've seen that I'm not supposed to update a use state in a loop but I am new to this and dont really see a way to get all the names to populate an array.




Aucun commentaire:

Enregistrer un commentaire