Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push elements to react hooks state array

I am using react-bootstrap-table2 to make HTML tables, I am using a checkbox inside my table to delete the items.

SO as per This link, it is mentioned how to get the selected row and then do the next part, here what I am doing is when I click on any checkbox row gets selected, and if I again select any row that I am adding to the array into my state like below

onSelect: (row, isSelect, rowIndex, e) => {
        if (isSelect === true) {
            setrowData((rowData) => [...rowData, row]);
        } else {
        //  here i need to do something
        }
    },

My issue is when I unselect the row that value is not getting deleted from my array, and at the time of delete, I have all the data which I have selected once.

  • One more thing which is related to this is when I check any row I want to show delete button and when none of the rows is checked I want to hide the delete button, here select is giving me the boolean value for that, but it is working for each select once I am selecting multiple rows it shows up, but when I unselect any one of them the delete button hides

What I have done for that is something like below

setrowSelect((rowSelect) => [...rowSelect, isSelect]); // this one is inside onSelect callback given by the react-bootstrap-table2 library

           {rowSelect && (
                    <button className="btn Secondary_Button_with_Icon">
                        <i className="ri-upload-cloud-line ri-lg"></i>Register
                    </button>
                )}

My full working code

like image 781
vivek singh Avatar asked Jun 15 '26 17:06

vivek singh


1 Answers

Use a filter method inside your else block to remove that unselected element from the array

 onSelect: (row, isSelect, rowIndex, e) => {
      if (isSelect === true) {
        setrowData((rowData) => [...rowData, row]);
      } else {
        setrowData((rowData) => rowData.filter((x,i)=>i!==rowIndex))
      }
      setrowSelect((rowSelect) => [...rowSelect, isSelect]);
    },
like image 183
Eugen Sunic Avatar answered Jun 18 '26 05:06

Eugen Sunic