Data Grid - Column visibility
Define which columns are visible.
By default, all the columns are visible. The column's visibility can be switched through the user interface in two ways:
- By opening the column menu and clicking the Hide menu item.
- By clicking the Columns menu and toggling the columns to show or hide.
You can prevent the user from hiding a column through the user interface by setting the hideable
in GridColDef
to false
.
In the following demo, the "username" column cannot be hidden.
Initialize the visible columns
To initialize the visible columns without controlling them, provide the model to the initialState
prop.
<DataGrid
initialState={{
columns: {
columnVisibilityModel: {
// Hide columns status and traderName, the other columns will remain visible
status: false,
traderName: false,
},
},
}}
/>
Controlled visible columns
Use the columnVisibilityModel
prop to control the visible columns.
You can use the onColumnVisibilityModelChange
prop to listen to the changes to the visible columns and update the prop accordingly.
<DataGrid
columnVisibilityModel={{
// Hide columns status and traderName, the other columns will remain visible
status: false,
traderName: false,
}}
/>
Column visibility panel
The column visibility panel can be opened through the Data Grid toolbar.
To enable it, you need to add toolbar: GridToolbar
to the Data Grid slots
prop.
The user can then choose which columns are visible using the Columns button.
Customize the list of columns in panel
To show or hide specific columns in the column visibility panel, use the slotProps.columnsPanel.getTogglableColumns
prop. It should return an array of column field names.
const getTogglableColumns = (columns: GridColDef[]) => {
// hide the column with field `id` from list of togglable columns
return columns
.filter((column) => column.field !== 'id')
.map((column) => column.field);
};
<DataGrid
slots={{
toolbar: GridToolbar,
}}
slotProps={{
columnsPanel: {
getTogglableColumns,
},
}}
/>;
Disable action buttons
To disable Hide all
or Show all
buttons in the column visibility panel, pass disableHideAllButton
or disableShowAllButton
to slotProps.columnsPanel
.
<DataGrid
slots={{
toolbar: GridToolbar,
}}
slotProps={{
columnsPanel: {
disableHideAllButton: true,
disableShowAllButton: true,
},
}}
/>