1

I am using mantine react table in my application for showing the data on UI. In this single selection table i want to get the selected row details and want to call a function in which i need to set one state with the help of selected row details.

 const someFunction = () => {
    props.selectedRow({
    id: rowDetails.id,
    rowData: rowDetails,
    });
};
<MantineReactTable
                        columns={tableHeader}
                        data={tableData}
                        enableColumnActions={true}
                        enableColumnFilters={true}
                        enablePagination={true}
                        enableSorting={true}
                        enableTopToolbar={true}
                        enableRowSelection={true}
                        muiSelectCheckboxProps={{
                          color: 'secondary',
                        }}
                        enableStickyHeader
                        enableStickyFooter
                        enableSelectAll={false}
                        enableMultiRowSelection={false}
                      /> 

So i want to call someFunction everytime i select a row and want to set props.selectedRow value with the current selected row value. How can i do that?

Sunny
  • 708
  • 1
  • 4
  • 21
rrahul789
  • 23
  • 6

1 Answers1

0

First, create a toggleRow() function that will set which row is currently selected and a State object to hold it in, as well as call your function someFunction(). This particular implementation will also allow you to click the same row again to deselect, but you can remove that if you don't need it.

const [selection, setSelection] = useState('');
const toggleRow = (id: string) =>
    setSelection((current) =>
        current == id ? current = '' : current = id
    );
    someFunction()

Now we map this function onto the row components from our data, making toggleRow() the onClick() function.

const rows = events.map((item) => {
    const selected = selection.includes(item.id);
    return (
        <tr key={item.id} className={cx({ [classes.rowSelected]: selected })} onClick={() => toggleRow(item.id)}>
            <td/>
            <td/>
            <td/>
        </tr>

Finally, we'll create a styles class which will highlight the row we have selected. Entirely optional, but a nice UI touch.

rowSelected: {
    backgroundColor:
          theme.colorScheme === 'dark'
              ? theme.fn.rgba(theme.colors[theme.primaryColor][7], 0.2)
              : theme.colors[theme.primaryColor][0],
  },
Stitt
  • 406
  • 2
  • 8