How do I save column state using Material-UI DataGrid?

Viewed 1012

I have multiple tables, each with 19 columns. The columns are all the same, but the data shown is different and comes from an external DB. I want the user to be able to select which columns they want to hide/show, and apply that to each table rendered.

I understand using Context to save the state, and that's where I'm leaning. I guess my question is more of "What do I need to save from the Column component in order to save the state of each column"?

1 Answers

It is certainly possible. Here is how I am saving the state of columns.

I have used componentsProps property and onChange.

Here is exact code

 <DataGrid
     rows={rows}
     componentsProps={{                     
      preferencesPanel: {
                        onChange: event => {
                            const tempCols = [...columns];
                            //const hideCol = '';'
                            tempCols.forEach((col, i) => {
                                if (col.field === event.target.name) {
                                    tempCols[i].hide = !tempCols[i].hide;
                                    //  hideCol = hideCol.concat(col.field + ',');
                                }
                            });
                            setColumns(tempCols);
                        }
                    }

 />
 
 <Button color="primary" onClick={() => 
        methodNametoSavestate(columns)}>
                    Save as preference
                </Button>
Related