Material-UI : DataGrid/XGrid How to detect density change?

Viewed 1500

I want to change action icon size when user change density table: The Pen icon on the right should change size when row is smaller, like this: enter image description here

For the moment i use onStageChange to capture all change on table and set a state variable on component

           ...
           const [density, setDensity] = useState<GridDensity>();
           ...
           const actionEdit: GridColDef = {
            field: '',
            type: 'action',
            align: 'right',
            disableColumnMenu: true,
            disableClickEventBubbling: true,
            resizable: false,
            flex: 1,
            headerClassName: 'edit-theme-header',
            cellClassName: 'edit-theme-cell',
            renderCell: () => <EditAction size={density} onClick={() => alert('click')} />
          };
           ... 
           <XGrid
                .....
                onStateChange={(v) => setDensity(v.state.density.value)}
            />

It works but onStateChange is called for all state change (not only density). Is there a better way to do ? :)

2 Answers

You could declare another state for icon size and change it inside onStateChange.

onStateChange={(v) => {
  setDensity(v.state.density.value);
  // HERE SET ICON SIZE STATE
}

then, use that state value as the icon size prop.

My solution is based on @mdmundo answer.

...
const [density, setDensity] = useState<GridDensity>('compact');
...
<XGrid
    ...
    className={density === 'compact' ? 'compact' : ''}
    onStateChange={v => density !== v.state.density.value && setDensity(v.state.density.value)}
/>

A little style:

.MuiXGrid-root.compact {
   /* some style */
}
Related