Reputation: 223
I want to lock the first column of MUI v5 DataGrid. I know there is a feature(via prop) to do that in DataGrid Pro but I can't afford that so I thought that I will make the first column both first header column and first body column via CSS. I was able to achieve somewhat I needed but not able to make it work properly. I am facing 1 issue: 1.Although the first body column is getting locked via position sticky but first header column is not getting locked. I have set the columnBuffer to the length of the columns to avoid virtualization also meaning my first column will be the first column irrespective of whether it's present in view or not.
<DataGrid
sx={{
'.MuiDataGrid-virtualScroller': {
height: '260px !important',
overflowY: 'auto',
},
'& .MuiDataGrid-cell:first-child': {
position: 'sticky',
top: '0',
left: '0',
paddingLeft: '1.5rem',
zIndex: 999,
},
'& .MuiDataGrid-columnHeader:first-child': {
position: 'sticky',
top: '0',
left: '0',
paddingLeft: '1.5rem',
border: 'none',
zIndex: 999,
},
}}
columnBuffer={columns.length}/>
Upvotes: 0
Views: 3905
Reputation: 1
My main language is not English, I apologize in advance if any phrase does not have the correct grammatical meaning.
I implemented the CSS style base that you indicate in your question, and I made the following modifications:
To affect the first cell of the header that was not fixed in its position, I applied the styles as follows:
"& .MuiDataGrid-columnHeaders": {
"& .MuiDataGrid-columnHeadersInner": {
transform: "none !important",
"& div": {
"& .MuiDataGrid-columnHeader:first-child": {
backgroundColor: "#FFFFFF",
zIndex: 2,
},
},
},
},
I used a useEffect, to add a Scroll event, on the HTML element, which has the .MuiDataGrid-virtualScroller class.
useEffect(() => {
const findVirtualScroller = () => {
const virtualScrollerElement = document.querySelector(
".MuiDataGrid-virtualScroller"
);
if (!virtualScrollerElement) {
setTimeout(findVirtualScroller, 100);
} else {
virtualScrollerElement.addEventListener(
"scroll",
handleScrollHorizontal
);
return () => {
virtualScrollerElement.removeEventListener(
"scroll",
handleScrollHorizontal
);
};
}
};
findVirtualScroller();
}, []);
Finally, I applied a transform, translate directly to the datagrid headers, individually.
const handleScrollHorizontal = () => {
const currentScrollPos = document.querySelector(
".MuiDataGrid-virtualScroller"
).scrollLeft;
const columnsHeaders = document.querySelectorAll(
".MuiDataGrid-columnHeader:not(.MuiDataGrid-columnHeader:first-child)"
);
columnsHeaders.forEach((columnHeader) => {
columnHeader.style.transform = `translate3d(-${currentScrollPos}px, 0px, 0px)`;
});
};
I hope this can work as a guide to solve the problem you mention.
Greetings.
Upvotes: 0