6

I have a fairly simple datagrid table with the option to hide/show specific columns. I want to save the state of the columns when a rerender occurs (in my case when the language is changed).

Here is a stripped down sample. Just hide a column and then click the button. The column-header change as expected but the hidden column reappears.

https://codesandbox.io/s/material-demo-forked-lq22m

I think I have to set the hide property correctly to the current state of the columns in my click handler:

 const handleButtonClick = () => {
    setColumnState((c) => c.map((d) => ({ ...d, hide:currentStateofHideForEachCol, headerName: "nombre" })));
  };

But I cant find a way to access it.

user15410756
  • 61
  • 1
  • 2
  • I need that too (access to current column visibility, change events), any idea how to get event on column visibility change? – user3086678 May 06 '21 at 11:40

1 Answers1

0

Currently, by updating columnState you are forcing a rerender of a new grid instead of updating the current one, thus losing the state.

I changed your code behavior so it now uses GridColDef.renderHeader and React.useContext to change the column names based on the language without losing the grid's state.

In terms of saving the state of the grid, the whole state of the grid is not controllable, making it difficult to do so, particularly the columns' visibility is not accessible. However, other props (the sort, filter, and selection models) can be controlled. For example, you can control the page prop:

// This mimics the default page change behavior 
const [currentPage, setCurrentPage] = useState(1);
const handleChangePage = useCallback(
 (gridPageChangeParams)=> setCurrentPage(gridPageChangeParams.page),
  []
);
<DataGrid page ={currentPage} onPageChange={handleChangePage}
David I. Samudio
  • 2,364
  • 18
  • 21