score:0
fortunately, the datagrid api provides the columnvisibilitymodel
and oncolumnvisibilitychange
props.
see this code sandbox for a simple example of controlling the columnvisibilitymodel
: https://codesandbox.io/s/mui-datagrid-oncolumnvisibilitychange-savestate-u1opzc?file=/src/app.tsx:1960-1984
here is the code for a simple implementation. your initial state may vary. also, note that i could not figure out how to get datagridpro to call oncolumnvisibilitychange
unless columnvisibilitymodel
was initially undefined. bug, or my mistake, i am uncertain.
import "./styles.css";
import react from "react";
import {
datagrid,
gridrowsprop,
gridcoldef,
gridcallbackdetails,
muievent,
gridcolumnvisibilitymodel,
gridcolumnvisibilitychangeparams
} from "@mui/x-data-grid";
import { button } from "@mui/material";
const rows: gridrowsprop = [
{ id: 1, col1: "hello", col2: "world" },
{ id: 2, col1: "datagridpro", col2: "is awesome" },
{ id: 3, col1: "mui", col2: "is amazing" }
];
const columns: gridcoldef[] = [
{ field: "col1", headername: "column 1", width: 150 },
{ field: "col2", headername: "column 2", width: 150 }
];
const initialvisibilitymodel = { col1: true, col2: true };
export default function app() {
// it is strange, but in order for datagridpro to call oncolumnvisibilitychange, columnvisibilitymodel must be undefined initially
const [
currentgridcolumnvisibilitymodel,
setcurrentgridcolumnvisibilitymodel
] = react.usestate<gridcolumnvisibilitymodel | undefined>(undefined);
const [mysavedvalue, setmysavedvalue] = react.usestate<
gridcolumnvisibilitymodel | undefined
>(undefined);
const oncolumnvisibilitychange = react.usecallback(
(
params: gridcolumnvisibilitychangeparams,
event: muievent<{}>,
details: gridcallbackdetails
): void => {
console.log("params", params);
setcurrentgridcolumnvisibilitymodel((s) => ({
// per the datagridpro strangeness, we must marry in initial state only the first update
...(s ? s : initialvisibilitymodel),
[params.field]: params.isvisible
}));
},
[]
);
const saveacopyofgridstate = () => {
setmysavedvalue(currentgridcolumnvisibilitymodel || initialvisibilitymodel);
};
const loadsavedcopyofgridstate = () => {
setcurrentgridcolumnvisibilitymodel(mysavedvalue || initialvisibilitymodel);
};
const currentvisibilityastext =
`${object.keys(currentgridcolumnvisibilitymodel ?? {}).map(
(key) => `{${key}:${currentgridcolumnvisibilitymodel?.[key]}}`
)}` || "empty";
const savedvisibilityastext =
`${object.keys(mysavedvalue ?? {}).map(
(key) => `{${key}:${mysavedvalue?.[key]}}`
)}` || "empty";
return (
<div style={{ height: 300, width: "100%" }}>
<datagrid
rows={rows}
columns={columns}
columnvisibilitymodel={currentgridcolumnvisibilitymodel}
oncolumnvisibilitychange={oncolumnvisibilitychange}
/>
<div>
<button onclick={saveacopyofgridstate} variant="contained">
save current column visibility state
</button>
<button
onclick={loadsavedcopyofgridstate}
variant="contained"
color="warning"
>
load saved column visibility state
</button>
</div>
<p>current filter state: {currentvisibilityastext}</p>
<p>saved filter state: {savedvisibilityastext}</p>
</div>
);
}
Source: stackoverflow.com
Related Query
- Material-UI DataGrid/DataGridPro: How to persist state of columns through re-render, when you change their visibility with DataGrid Column Toolbar
- How to make DataGrid columns start from right side Material UI
- How can I persist redux state tree on refresh?
- How do I pass state through React_router?
- How does react-router persist location state over page refreshes?
- How to persist state across react router transitions
- How to persist redux state data in Next.js?
- How to update React component after changing state through redux?
- How do I persist state in local storage React without Redux?
- How to persist redux state in the easiest way?
- How to import ReactJS Material UI using a CDN through Webpack's externals?
- How to sort a Material UI DataGrid column programatically?
- How to save state of column visibility in material ui data grid
- How to NOT persist state between Next.js dynamic routes?
- How to set component state based on Material UI selected table rows
- How to persist state in Xstate state machines in react?
- How can I persist React-native redux state using redux-persist?
- How do I pass a React Context's state through an onClick function created in a method inside that context class?
- How to pass multiple state through link in ReactJS
- React - how to handle a cell click of a specific column of a datagrid table of material ui?
- How to update the state after a data update through an API request in React?
- Material UI DataGrid - how to tell which rows user has selected?
- How to disable some specific columns from edit in react material table?
- React state keeps resetting on form submittal. How to persist state?
- How I can loop through the similar objects in state and push them into object?
- Material UI React - Autocomplete - How to reset the internal state
- How do I override checkbox color (box and font) in disabled state in material ui?
- How to maintain state of child components when they are filtered through the parent component?
- How to pass array items through state
- How can I have two headers columns for the same column in a material UI table?
More Query from same tag
- Making components with curly brackets versus parenthesis when using functional components
- styling css by confdition from the backend
- Pass values from children to parent component
- How to get js-cookies?
- react two json object merge and result: empty slots
- React hooks JSX rendering not working properly
- npm install unable to resolve dependency tree
- React router dom's Link not working properly
- how to run an already ready app in react js with npm
- Inserting text with execCommand causes a duplication issue
- react-three-fiber rotate around a certain axis
- Persist some attributes with redux-persist does not work
- how to create React Context for a function value without re-rendering all the time
- Default value with react-select, checkboxes not working when I want to post my data having a blank page output
- How to redraw text rendered using SVGRenderer in Highcharts React?
- Cannot Resize React Barcode to the defined width and height
- how to make 1st tab of accordian open by default in reactjs
- Focus Select element
- Fetching user details in React from django-rest-auth gives back 403 (Forbidden) - Using authtoken
- Trivial issue with React setState function
- how to get screenshot of gltf model in javascript?
- React interaction between components
- interface is not assignable to type Record<string, unknown>
- How to integrate a Nodejs API with ReactJs app under the same domain
- How can I use typescript to destructure from a complex type?
- React - How to build a custom hook?
- React semantic ui table.row set row active onclick
- The request is missing a Valid API Key while using Youtube Data API v3
- ReactJS - SVG - Interactive Timeline
- How to handle one-time event across components in React?