How can i hide a column in MUI? - reactjs

I don't wanna show id field of my table.I use "#mui/x-data-grid":"^5.6.1" version. Here is my code;
import * as React from 'react';
import { DataGrid } from '#mui/x-data-grid';
const columns = [
{ field: 'id', headerName: 'ID', width: 50},
{ field: 'testName', headerName: 'Test Name', width: 120,},
{ field: 'testDate', headerName: 'Test Date', width: 160 },
];
export default function DataTable(props) {
const rows = [id:1, testName:"test", testDate:"23/03/2022"];
return (
<div id="resultTable" >
<DataGrid
rows={rows}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
/>
</div>
);
}
Id column can be hidden or display:none. I tried to use
display:false
or:
hidden: true
and also tried:
options: {display: false, filter: false,}
but it wasnt work.

I found the solution.
{ field: 'id', headerName: 'ID', width: 50, hide: true}
This is enough for me.

According to MUI documentation, hide: true is now deprecated.
Instead you should use the Column Visibility Model.
Example from the documentation:
<DataGrid
initialState={{
columns: {
columnVisibilityModel: {
// Hide columns status and traderName, the other columns will remain visible
status: false,
traderName: false,
},
},
}}
/>

Expanding on Robinson's answer from the docs There's also a way to do this programmatically. I used this code to hide some columns on mobile version.
export const MOBILE_COLUMNS = {
id: true,
value: true,
value2: false,
value3: false,
};
export const ALL_COLUMNS = {
id: true,
value: true,
value2: true,
value3: true,
};
const theme = useTheme();
const matches = useMediaQuery(theme.breakpoints.up("sm"));
const [columnVisible, setColumnVisible] = React.useState(ALL_COLUMNS);
React.useEffect(() => {
const newColumns = matches ? ALL_COLUMNS : MOBILE_COLUMNS;
setColumnVisible(newColumns);
}, [matches]);
return (
<DataGrid
rows={rows}
columns={columns}
columnVisibilityModel={columnVisible}
/>
)

GridColDef.hide prop is deprecated, you should use the column visibility to hide the unwanted columns: https://mui.com/x/react-data-grid/columns/#controlled-visible-columns

I know that this question is already answered, but what I encountered was that I needed to hide a field but retrieve its value once I edit a row, which is also what OP commented on one of the answers.
The solution for this is adding the editable prop to the field like so:
{field: 'id', hide: true, editable: true}

Try removing the first object in columns array like so
const columns = [
//{ field: 'id', headerName: 'ID', width: 50}, //or delete it entirely
{ field: 'testName', headerName: 'Test Name', width: 120,},
{ field: 'testDate', headerName: 'Test Date', width: 160 },
]
or add the property hide: true and editable: true
const columns = [
{ field: 'id', headerName: 'ID', width: 50, hide: true, editable: true},
{ field: 'testName', headerName: 'Test Name', width: 120,},
{ field: 'testDate', headerName: 'Test Date', width: 160 },
]

Related

How to add MUI DataGrid Edit/delete Button

I am having a hard time adding custom buttons per row in the DataGrid component.
This is my code:
const columns = [
{ field: 'model_id', headerName: 'ID', width: 70, sortable: false },
{ field: 'model_code', headerName: 'Model Code', width: 130 },
{ field: 'model_description', headerName: 'Description', width: 400 },
{ field: 'actions', headerName: 'Actions', width: 400 }
];
DataGrid:
<DataGrid
rows={models}
columns={columns}
getRowId={(row) => row.model_id}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection />
What I want per row:
You can use renderCell function in column definition array like this:
const onButtonClick = (e, row) => {
e.stopPropagation();
//do whatever you want with the row
};
const columns = [
{ field: 'model_id', headerName: 'ID', width: 70, sortable: false },
{ field: 'model_code', headerName: 'Model Code', width: 130 },
{ field: 'model_description', headerName: 'Description', width: 400 },
{ field: 'actions', headerName: 'Actions', width: 400, renderCell: (params) => {
return (
<Button
onClick={(e) => onButtonClick(e, params.row)}
variant="contained"
>
Delete
</Button>
);
} }
];
You can take a look at this sandbox for a live working example of this solution.

Passing an Image in Material-UI Data-Grid Table

there. I would like to add an image in a material-ui data-grid table. But it's not working. What am I missing here? I tried to search the docs but couldn't see any example that used images.
My code
import { DataGrid } from '#material-ui/data-grid';
const columns = [
{
field: 'image',
headerName: 'Image',
width: 150,
editable: true,
},
{
field: 'name',
headerName: 'Name',
width: 150,
editable: true,
},
];
const rows = [
{
id: 1,
image: "image URL",
type: 'image',
name: 'Cheese Burger',
price: 10_000,
menu: 'Daily Menu',
category: 'Burgers'
},
{
id: 2,
image: "image URL",
name: 'Diet Coke',
price: 10_000,
menu: 'Daily Menu',
category: 'Driks'
},
];
export const ItemsTable = () => {
return (
<div style={{ height: 300, width: '100%' }} className="mt-7">
<DataGrid
rows={rows}
columns={columns}
pageSize={5}
checkboxSelection
disableSelectionOnClick
/>
</div>
);
}
Desired result
What's I'm getting
The renderCell prop allows you to inject components into the DataGrid, creating a column of custom cells.
https://smartdevpreneur.com/add-buttons-links-and-other-custom-cells-in-material-ui-datagrid/#How_to_Add_Other_Custom_Components
Material-Ui's documentation on renderCell.
https://mui.com/components/data-grid/columns/#render-cell
Just need to pass in the value into the image component src.
I made a codesandbox to show renderCell in action.
https://codesandbox.io/s/rendercellgrid-material-demo-edq5p?file=/demo.js
const columns = [
{
field: 'image',
headerName: 'Image',
width: 150,
editable: true,
renderCell: (params) => <img src={params.value} />, // renderCell will render the component
},
{
field: 'name',
headerName: 'Name',
width: 150,
editable: true,
},
];

Unique id property could not be found from Material-UI Datagrid

Error: Material-UI: The data grid component requires all rows to have a unique id property. I am seeing when I call the table.
Here is my code. I know that the _turbineId field is unique in the dataset.
Here is how I have the table defined.
const columns = [
{
field: "siteName",
headerName: "Wind Farm",
width: 150,
editable: true,
},
{
field: "turbineName",
headerName: "Turbine Name",
width: 150,
editable: true,
},
{
field: "controller",
headerName: "Controller Type",
type: "number",
width: 110,
editable: true,
},
{
field: "swVersion",
headerName: "Software Version",
type: "number",
width: 110,
editable: true,
},
{
field: "location",
headerName: "Country",
type: "number",
width: 110,
editable: true,
},
{
field: "_turbineId",
headerName: "Turbine Name",
type: "number",
width: 110,
},
];
Here is how I define the rows
const rows = windFarmData.map((data) => [
{
siteName: data.SiteName,
turbineName: data.TurbineName,
controller: data.Controller,
swVersion: data.SoftwareVersion,
location: data.Country,
_turbineId: data.TechnicalId,
},
]);
Here is the datagrid
export default function DataTable() {
return (
<div style={{ height: 400, width: "100%" }}>
<DataGrid
getRowId={(r) => r._turbineId}
rows={rows}
columns={columns}
pageSize={5}
checkboxSelection
disableSelectionOnClick
/>
</div>
);
}
I wonder if I have missed something or done something wrong.
It works now. I replaced this:
const rows = windFarmData.map((data) => [
{
siteName: data.SiteName,
turbineName: data.TurbineName,
controller: data.Controller,
swVersion: data.SoftwareVersion,
location: data.Country,
_turbineId: data.TechnicalId,
},
]);
with this:
const rows = sortWindFarmData;

How to dynamically add the valueOptions of a singleSelect column in Material-UI's DataGrid?

This is my second question in SO, so apologize for any error in asking and formatting my question. I've been trying to accomplish what the tile said. Basically I have the following example of an array that I use to define my columns:
[
{
field: 'name',
headerName: 'Name',
flex: 1,
editable: true
},
{
field: 'address',
headerName: "Address",
flex: 1,
editable: true
},
{
field: 'country',
headerName: "Country",
flex: 1,
editable: true,
type: 'singleSelect',
valueOptions:
[
// This should be dynamic
]
},
]
This is exported from a separate file, which is then imported in the React component that uses the DataGrid with these columns definitions.
The options are fetched from my REST API when a user logs in and they will be different for each user.
Is there anyway I could assign the valueOptions for the column country dynamically after the initial definitions?
Thank you!
P.S: I'm using the free version of Material-UI's DataGrid.
You could change the value of the "valueOptions" field after you have the answer of your REST service:
fetch("your endpoint").then(answer => {
columnsConfig.filter(column => column.field === "country").valueOptions = answer;
})
PS: you may have to transform the answer before setting the value of valueOptions
valueOpt accepts a function that you can use to dynamically reference the values you are looking for.
Relevant issue:
https://github.com/mui/mui-x/issues/3528
[{
field: 'country',
headerName: "Country",
flex: 1,
editable: true,
type: 'singleSelect',
valueOptions: ({id, row, field}) => {
//return valueOptions for the row here
}
}]
you can do by valueOptions field
const types = { // get value from services }
{
field: 'country', width: 180,
headerName: 'Country',
type: 'singleSelect',
editable: true,
valueOptions: ({ row }) => { const options = [];
types?.map((type) =>options.push(type.name))
return options
}
},

Read the sum value from the column footer in UI - Grid?

I'm currently trying to read my column footer to make sure that the total sum from the aggregate is exactly 100. However I can not find a way to get that value from the grid functions. Maybe I missed a function in the docs. Is there a way to accomplish this or will I have to manually loop through my grid and sum the values?
You can use aggregates on the column footer to automatically show the sum of all the values in the column.
you can have your grid config like below
$scope.gridOptions = {
showGridFooter: true,
showColumnFooter: true,
enableFiltering: true,
columnDefs: [
{ field: 'name', width: '13%' },
{ field: 'address.street',aggregationType: uiGridConstants.aggregationTypes.sum, width: '13%' },
{ field: 'age', aggregationType: uiGridConstants.aggregationTypes.avg, aggregationHideLabel: true, width: '13%' },
{ name: 'ageMin', field: 'age', aggregationType: uiGridConstants.aggregationTypes.min, width: '13%', displayName: 'Age for min' },
{ name: 'ageMax', field: 'age', aggregationType: uiGridConstants.aggregationTypes.max, width: '13%', displayName: 'Age for max' },
{ name: 'customCellTemplate', field: 'age', width: '14%', footerCellTemplate: '<div class="ui-grid-cell-contents" style="background-color: Red;color: White">custom template</div>' },
{ name: 'registered', field: 'registered', width: '20%', cellFilter: 'date', footerCellFilter: 'date', aggregationType: uiGridConstants.aggregationTypes.max }
],
data: data,
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
}
};
http://plnkr.co/edit/nv1eJAIyD5xNDn8XI6L9?p=preview
To get the value from the footer, provided you know the column index and have a reference to the gridApi.
$scope.getFooterValue = function()
{
console.log($scope.gridApi);
alert($scope.gridApi.grid.columns[2].getAggregationValue());
}

Resources