Adjust visibility of columns in React JS Material UI-X Data Grid element

The React JS Material UI-X library has the Data Grid module for displaying data as a table. The requirement was to set the visibility of certain columns in the data grid to hidden with an option for the user to make it visible through UI. If we filter the data from the data source, user will not be able to do this. We can use the ‘GridColumnVisibilityModel’ property of the data grid and the user will be able to show the columns through teh ‘manage columns’ menu in the data grid. Here is the sample code for the same:

import { DataGrid, GridColDef, gridClasses, GridPagination, GridColumnVisibilityModel  } from ‘@mui/x-data-grid’;

const App = () => {

.

const [columnVisibilityModel, setColumnVisibilityModel] = useState<GridColumnVisibilityModel>(JSON.parse(localStorage.getItem(‘columnVisibilityModel’) as string) || {});

useEffect(() => { localStorage.setItem(‘columnVisibilityModel’, JSON.stringify(columnVisibilityModel)); }, [columnVisibilityModel]); // Store column visibility values in localStorage

const handleColumnVisibilityChange = (newModel: Record<string, boolean>) => {

    setColumnVisibilityModel(newModel);

  };

 <DataGrid

            rows={rows}

            columns={columns}

            columnVisibilityModel={columnVisibilityModel}

            onColumnVisibilityModelChange={handleColumnVisibilityChange}

   />

……

}

Leave a comment

Your email address will not be published. Required fields are marked *