reactjsreact-bootstrapreact-bootstrap-table

How to dynamically disable a row's checkbox in react-bootstrap-table2?


I want to achieve something that is in my current sandbox:

enter image description here

Currently I've hardcoded the nonSelectable: [1, 2] so it will make row 1 and 2 unselectable.

Now I want to make the rows unselectable based on the file's createdByID.

If the file's createdByID is same with the user's login ID, then it will be selectable, else it won't, but my issue now is that how do I get each row's data and compare their createdByID with the user's ID then return the indexes that needs their checkbox to be disabled as an array to the nonSelectable prop?

I've found this link but I'm not quite sure how to get it work as I am not sure where to get the key.

CodeSandbox Demo


Solution

  • You can create a function to generate the nonSelectable array programmatically for you. For example

    function getNonSelectableRows(rows, userLoginId) {
      return rows
        .filter((r) => r.createdByID !== userLoginId)
        .reduce((acc, r) => {
          acc.push(r.fileID);
          return acc;
        }, []);
    }
    

    Then call the function for selectRow.nonSelectable

    function App() {
      ...
      // I don't see the user login id in your code.
      // Thus I just add it as a constant at the top.
      const userLoginId = '200201';
      const [files] = useState([
        {
          fileID: 1,
          fileName: "Cardio Care Awareness Month",
          createdByID: "100101"
        },
        {
          fileID: 2,
          fileName: "MEMO COMPULSORY TO",
          createdByID: "100101"
        },
        {
          fileID: 3,
          fileName: "MEMO 2021 Covid19 Vaccination Leave",
          createdByID: "200201"
        },
        {
          fileID: 4,
          fileName: "Human Cell",
          createdByID: "200201"
        }
      ]);
    
      const selectRow = {
        mode: "checkbox",
        // nonSelectable = [1, 2]
        nonSelectable: getNonSelectableRows(files, userLoginId),
      ...