跳转到内容

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.

<DataGrid
  columns={[
    { field: 'username', hideable: false },
    { field: 'age' },
    { field: 'desk' },
  ]}
  rows={rows}
  components={{
    Toolbar: GridToolbar,
  }}
/>

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,
  }}
/>
<DataGrid
  {...data}
  loading={loading}
  columnVisibilityModel={columnVisibilityModel}
  onColumnVisibilityModelChange={(newModel) =>
    setColumnVisibilityModel(newModel)
  }
/>

Column visibility panel

The column visibility panel can be opened through the grid toolbar. To enable it, you need to add Toolbar: GridToolbar to the grid components prop.

The user can then choose which columns are visible using the Columns button.

<DataGrid
  {...data}
  components={{
    Toolbar: GridToolbar,
  }}
/>

Column hide property (deprecated)

Before the introduction of the columnVisibilityModel, the columns could be hidden by setting the hide property in GridColDef to true. This method still works but will be removed on the next major release.

<DataGrid
  columns={[
    { field: 'username', hideable: false },
    { field: 'age', hide: true },
    { field: 'desk' },
  ]}
  rows={rows}
/>