Display row data of all columns upon selecting row or checkbox in MUI datatable - javascript

I have a MUI datatable. The properties are defined as follows
data={serialsList || []}
columns={columns}
options={{
...muiDataTableCommonOptions(),
download: false,
expandableRowsOnClick: false,
search: false,
page: currentPage,
rowsPerPage: numberOfRows,
count: serialsTotalCounts,
selectableRows: this.state.cancelShipFlag ? 'multiple' : 'none',
selectableRowsHeader: this.state.cancelShipFlag ? true : false,
selectToolbarPlacement: 'none',
onRowSelectionChange(currentRowsSelected, allRowsSelected, rowsSelected?) {
console.log(currentRowsSelected, allRowsSelected, rowsSelected);
},
//selectableRowsHideCheckboxes: this.state.cancelShipFlag ? true : false,
onRowClick: (rowData, rowMeta) => console.log('onRowsSelect.', rowData, rowMeta),
I want to display the entire row contents as a Json or string if I select a particular row or a checkbox in that row. How do I do this?
I have read that we can use
getSelectedRows: () => Map<GridRowId, GridRowModel>
But i am not sure how to use it. Can someone guide me in this?
I have also seen this link for reference but not sure if it will work
Sandbox example

According by your example
// State for selected rows
const [selectedRows, setSelectedRows] = useState([]);
// Save selected rows to state
onRowSelectionChange: (currentSelect, allSelected) => {
setSelectedRows(allSelected);
}
// return as a JSON
<pre style={{ fontSize: 10 }}>
{JSON.stringify(selectedRows, null, 4)}
</pre>

Related

Access Ant Design table column value

I am trying to condionally render Bage based on status column value. Even though I can render the table with the status values, I cannot access the status column for each item for conditional rendering of status Badge. How do I access the values listed on the column ?
The "status" value is inside data [ ]
const tableColumns = columns.map((item) => ({
...item,
ellipsis,
}));
const columns = [
{
title: 'Статус',
dataIndex: 'status',
render: () => {dataIndex.status === "in progress" ? <Badge status="processing" text="in progress" /> : <Badge status="success" text="delivered" />}
},
]
<Table
{...tableProps}
pagination={{
position: [top, bottom],
}}
columns={tableColumns}
dataSource={hasData ? data : []}
scroll={scroll}
/>

customize pagination in React Material-Table

Above is image of jQuery datatable pagination. However I am not able to achieve similar pagination UI in react Material-Table (basically pagination should display last page number after initial page number ... seprated)
<MaterialTable
localization={{
pagination: {
// labelDisplayedRows: '{from}-{to} of {count}'
// labelDisplayedRows: '{currentPage}...{lastPage}'
},
toolbar: {
nRowsSelected: '{0} row(s) selected'
},
header: {
actions: 'Actions'
},
body: {
emptyDataSourceMessage: 'No records to display',
filterRow: {
filterTooltip: 'Filter'
}
}
}}
/>

How to make checkboxes appear conditionally in MUI Datatable

I have a MUI Datatable. While defining 'options' for the table, I am setting selectableRows: 'multiple', selectableRowsHeader: true,
This creates a table with the checkboxes for all rows and also the selectall checkbox on top. However, I want it to appear only when I click a certain button in the title. How do i do this?
My code snippet is as follows
columns={columns}
options={{
...muiDataTableCommonOptions(),
download: false,
expandableRowsOnClick: false,
search: false,
page: currentPage,
rowsPerPage: numberOfRows,
count: serialsTotalCounts,
selectableRows: 'multiple',
selectableRowsHeader: true,
onRowClick: (rowData, rowMeta) => console.log('onRowsSelect.', rowData, rowMeta),
customToolbar: () => (
<SerialsCustomToolbar
showAddSerialButton={false}
textSearched={(text) => {
//DISORIENTED_SERIALS_LISTING - optional callback to handle rendering while using search box
this.query['searchText'] = text;
this.setState({ initialized: false }, () => {
this.pages.limit = LIMIT_PAGINATION_MAX;
this.pages.offset = 0;
const query = Object.assign({}, this.query, this.pages);
this.updateQuery(query);
});
}}
This is is just the code relevant to the table options. How do i conditionally define those props for the table options element? I cant use if-else as this is jsx and inside the render().

How to hide a column on Material UI based on certain criteria?

I have a datagrid using MUI and I have came across a use case where I need to hide one of the columns if I do not have a certain role. Here is the code.
const hideColumn = () => {
const globalAdmin = auth.verifyRole(Roles.Admin);
if(!globalAdmin){
return true;
}
return false;
};
const columns = [
{ field: 'id', headerName: 'ID', width: 100 },
{ field: 'name',
headerName: 'Client code',
flex: 1,
hide: hideColumn,
renderCell: (params) => {
return params.getValue("name");
},
},
];
I'm confused on why this is not working. If I just use hide:true or hide:false it works but I need have an if statement to check the credentials first and this can't be done in the renderCell (or at least I can't get it to work). Does anyone know how to do this correctly?
You should call it as function hide: hideColumn()
Or you can create a function to retrieve your columns and pass props to this function. Then you just have to push your columns according to criteria:
export default function getColumns (product, isHide, t) {
let columns = [
{
field: 'organizationName',
headerName: headerNameOrganization,
flex: 0.3,
},
]
if (!product) {
columns.push(
{
field: 'status',
headerName: headerNameStatus,
flex: 0.2,
filterable: false,
})
}
return columns
}
Use the prop columnVisibilityModel of <DataGrid /> to control the column visibility dynamically.
The prop can also have a listener.
You can use the onColumnVisibilityModelChange prop to listen to the changes to the visible columns and update the prop accordingly.
(MUI doc)
At first, I was using the initialState (as the ff), but MUI said in their documentation:
The initialState can only be used to set the initial value of the state, the grid will not react if you change the initialState value later on.
If you need to fully control specific models, use the control props instead...
<DataGrid
columns={columns}
rows={rows}
loading={!users.length}
initialState={{
columns: {
columnVisibilityModel: {
myColumn1: isAdmin(user),
myColumn2: isAdmin(user),
},
},
}}
/>

refresh AgGrid and reselect last selected row

I am trying to refresh ag grid and reselect the last row before update.
This is my AG grid component.
onCellClicked = params => {console.log(params)
let node = params.node;
Promise.all([
node.setSelected(true, true),
this.props.actions.selectMarketingProspect(node.data),
this.props.actions.getMarketingCustomerNotes(this.props.dealerID,node.data.id)
]);
};
<AgGridReact
columnDefs={columnDefs}
defaultColDef={{
resizable: true,
sortable: true
}}
rowSelection='single'
getRowNodeId={data => data.id}
deltaRowDataMode={true}
frameworkComponents={frameworkComponents}
rowClassRules={this.state.rowClassRules}
detailCellRenderer={detailCellRenderer}
onFirstDataRendered={this.onFirstDataRendered}
onGridReady={this.onGridReady}
onSelectionChanged={this.onSelectionChanged}
onCellClicked={this.onCellClicked}
sideBar={toolPanelOptions}
onModelUpdated={this.onModelUpdated}
/>
</div>
Any ideas?
Based on what I read on the docs I believe that node.setselected should do the trick but I cant quite get there. Any help will be appreciated.
You can keep track of the last selected RowNode ids by listening to the selection changed event:
const [selectedRowIds, setSelectedRowIds] = React.useState<string[]>([]);
<AgGridReact
onSelectionChanged={(e) => {
const selectedNodes = e.api.getSelectedNodes();
if (selectedNodes.length === 0) return;
const selectedRowIds = selectedNodes
.map((n) => n.id)
.filter(Boolean) as string[];
setSelectedRowIds(selectedRowIds);
}}
{...}
/>
Then when you want to select it again, use GridApi.getRowNode(id) to get the RowNode you want to select and call RowNode.setSelected(true) to select it:
selectedRowIds.forEach((id) => {
gridApi?.getRowNode(id)?.setSelected(true);
});

Categories

Resources