New to KendoReactStart a free 30-day trial

Persisting the State of the KendoReact Grid

A common requirement for web apps is to save the user customization and settings when interacting with your app, and then restore them once the user comes back at some point in the future. The KendoReact Grid exposes the capability to save and restore settings that were previously applied.

The following example demonstrates how to persist the Grid state.

Change Theme
Theme
Loading ...

Setup

To persist the state of the Grid:

  1. Keep the initial skip, take and sort settings inside the dataState:

    jsx
    const [dataState, setDataState] = React.useState<GridState>({
        data: formattedOrders,
        total: formattedOrders.length,
        filter: { logic: 'and', filters: [] },
          skip: 0,
          take: 20,
          sort: [{ field: 'orderDate', dir: 'desc' }]
        });
  2. Define the current column configuration and render their state conditionally based on the data stored in localStorage:

    jsx
        const getInitialColumns = () => {
        const loadedColumns = localStorage.getItem('gridColumns');
        return loadedColumns
        ? JSON.parse(loadedColumns)
        : [
          { field: 'customerID', width: 200 },
          { field: 'orderDate', width: 200 },
          { field: 'shipName', width: 200 },
          { field: 'freight', width: 200 },
          { field: 'shippedDate', width: 200 },
          { field: 'employeeID', width: 200 },
          { field: 'orderID', width: 200 }
        ];
        }
        const [columns, setColumns] = React.useState(getInitialColumns);
  3. Create a saveStateToLocalStorage function that retrieves the current state and sets it in the localStorage:

    jsx
        const saveStateToLocalStorage = () => {
            const state = {
            dataState,
            columns
            };
            localStorage.setItem('gridState', JSON.stringify(state));
         };
  4. Create a loadStateFromLocalStorage function that retrieves the saved state from localStorage and sets the new data to the Grid:

    jsx
        const loadStateFromLocalStorage = () => {
            const savedState = localStorage.getItem('gridState');
        if (savedState) {
            const { dataState: savedDataState, columns: savedColumns } =
            JSON.parse(savedState)
            setDataState(savedDataState);
            setColumns(savedColumns);
            }
        };
In this article
SetupSuggested Links
Not finding the help you need?
Contact Support