---
title: "Row Sorting"
framework: react
version: "36.1.0"
---

# Row Sorting

This page describes how to sort row data in the grid and how you can customise that sorting to match your requirements.

## Sorting

Sorting is enabled by default for all columns. You can sort a column by clicking on the column header. To enable / disable sorting per column use the `sortable` column definition attribute.

```jsx
const [columnDefs, setColumnDefs] = useState([
    { field: 'name' },
    { field: 'age' },
    // disable sorting by address
    { field: 'address', sortable: false },
]);

<AgGridReact columnDefs={columnDefs} />
```

To disable sorting for all columns, set sorting in the [default column definition](https://www.ag-grid.com/react-data-grid/column-definitions/).

```jsx
// disable sorting on all columns
const defaultColDef = useMemo(() => { 
	return {
        sortable: false
    };
}, []);
const [columnDefs, setColumnDefs] = useState([
    // Override default to enable sorting by name
    { field: 'name', sortable: true },
    { field: 'age' },
    { field: 'address' },
]);

<AgGridReact
    defaultColDef={defaultColDef}
    columnDefs={columnDefs}
/>
```

## Custom Sorting

Custom sorting is provided at a column level by configuring a comparator on the column definition.

```jsx
const [columnDefs, setColumnDefs] = useState([
    {
        field: 'age',
        // simple number comparator
        comparator: (valueA, valueB, nodeA, nodeB, isDescending) => valueA - valueB
    },
    {
        field: 'name',
        // simple string comparator
        comparator: (valueA, valueB, nodeA, nodeB, isDescending) => {
            if (valueA == valueB) return 0;
            return (valueA > valueB) ? 1 : -1;
        }
    }
]);

<AgGridReact columnDefs={columnDefs} />
```

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `comparator` | `SortComparatorFn \| Partial<Record<SortType, SortComparatorFn>>` |  |  | Override the default sorting order by providing a custom sort comparator, or a map of comparators for different `SortType`s. - `valueA`, `valueB` are the values to compare. - `nodeA`, `nodeB` are the corresponding RowNodes. Useful if additional details are required by the sort. - `isDescending` - `true` if sort direction is `desc`. Not to be used for inverting the return value as the grid already applies `asc` or `desc` ordering. Returns: - `0` valueA is the same as valueB - `> 0` Sort valueA after valueB - `< 0` Sort valueA before valueB |

Example below shows the following:

- The **Athlete** column is sorted descending on load.
- When the **Year** column is not sorted, it shows a custom icon (up/down arrow).
- The **Date** column has strings as the row data, but has a custom comparator so that when you sort this column it sorts as dates, not as strings.

#### Custom Sorting

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import "./style.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";
import { useFetchJson } from "./useFetchJson";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [ClientSideRowModelModule];

function dateComparator(date1: string, date2: string) {
  const date1Number = monthToComparableNumber(date1);
  const date2Number = monthToComparableNumber(date2);
  if (date1Number === null && date2Number === null) {
    return 0;
  }
  if (date1Number === null) {
    return -1;
  }
  if (date2Number === null) {
    return 1;
  }
  return date1Number - date2Number;
}

// eg 29/08/2004 gets converted to 20040829
function monthToComparableNumber(date: string) {
  if (date === undefined || date === null || date.length !== 10) {
    return null;
  }
  const yearNumber = Number.parseInt(date.substring(6, 10));
  const monthNumber = Number.parseInt(date.substring(3, 5));
  const dayNumber = Number.parseInt(date.substring(0, 2));
  return yearNumber * 10000 + monthNumber * 100 + dayNumber;
}

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);

  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "athlete", sort: "desc" },
    { field: "age", width: 90 },
    { field: "country" },
    { field: "year", width: 120, unSortIcon: true },
    { field: "date", comparator: dateComparator },
    { field: "sport" },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      width: 170,
    };
  }, []);

  const { data, loading } = useFetchJson<IOlympicData>(
    "https://www.ag-grid.com/example-assets/olympic-winners.json",
    10,
  );

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={gridStyle}>
          <AgGridReact<IOlympicData>
            rowData={data}
            loading={loading}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Custom Sorting](https://www.ag-grid.com/examples/row-sorting/custom-sorting/reactFunctionalTs)

> **Note**
>
> If you are using a custom column header component see [Custom Components](https://www.ag-grid.com/react-data-grid/column-headers-components/#custom-component) for how to implement sorting.

## Multi Column Sorting

It is possible to sort by multiple columns. The default action for multiple column sorting is for the user to hold down `⇧ Shift` while clicking the column header. To change the default action to use the `^ Ctrl` key instead set the property `multiSortKey='ctrl'`.

The example below demonstrates the following:

- The grid sorts by **Country** then **Athlete** by default.
- The property `multiSortKey='ctrl'` is set so multiple column sorting is achieved by holding down `^ Ctrl` and selecting multiple columns.

#### Multi Column Sort

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  ColumnApiModule,
  ColumnState,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";
import { useFetchJson } from "./useFetchJson";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [ColumnApiModule, ClientSideRowModelModule];

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);

  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "athlete" },
    { field: "age", width: 100 },
    { field: "country" },
    { field: "year", width: 100 },
    { field: "date" },
    { field: "sport" },
    { field: "gold" },
    { field: "silver" },
    { field: "bronze" },
    { field: "total" },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      width: 170,
    };
  }, []);

  const onGridReady = useCallback((params: GridReadyEvent) => {
    const defaultSortModel: ColumnState[] = [
      { colId: "country", sort: "asc", sortIndex: 0 },
      { colId: "athlete", sort: "asc", sortIndex: 1 },
    ];
    params.api.applyColumnState({ state: defaultSortModel });
  }, []);
  const { data, loading } = useFetchJson<IOlympicData>(
    "https://www.ag-grid.com/example-assets/olympic-winners.json",
  );

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={gridStyle}>
          <AgGridReact<IOlympicData>
            rowData={data}
            loading={loading}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
            multiSortKey={"ctrl"}
            onGridReady={onGridReady}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Multi Column Sort](https://www.ag-grid.com/examples/row-sorting/multi-column/reactFunctionalTs)

> **Note**
>
> You can suppress the multi sorting behaviour by enabling the `suppressMultiSort` option, or force the behaviour without key press by enabling the `alwaysMultiSort` option.

## Sorting Animation

By default rows will animate after sorting. If you wish to suppress this animation set the grid property `animateRows=false`.

## Sorting Order

By default, the sorting order is as follows:

**ascending -> descending -> none**.

In other words, when you click a column that is not sorted, it will sort ascending. The next click will make it sort descending. Another click will remove the sort.

It is possible to override this behaviour by providing your own `sortingOrder` on the `colDef`.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sortingOrder` | `(SortDirection \| SortDef)[]` |  |  | An array defining the order in which sorting occurs (if sorting is enabled). Defaults: - `['asc', 'desc', null]` if no sort type is specified, - `[{ type: 'absolute', direction: 'asc', }, { type: 'absolute', direction: 'desc' }, null]` if 'sort' or 'initialSort' have type 'absolute' |

The example below shows different combinations of sorting orders as follows:

- **Column Athlete:** ascending -> descending
- **Column Age:** descending -> ascending
- **Column Country:** descending -> no sort
- **Column Year:** ascending only
- **Default Columns:** descending -> ascending -> no sort

#### Sorting Order and Animation

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";
import { useFetchJson } from "./useFetchJson";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [ClientSideRowModelModule];

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);

  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "athlete", sortingOrder: ["asc", "desc"] },
    { field: "age", width: 90, sortingOrder: ["desc", "asc"] },
    { field: "country", sortingOrder: ["desc", null] },
    { field: "year", width: 90, sortingOrder: ["asc"] },
    { field: "date" },
    { field: "sport" },
    { field: "gold" },
    { field: "silver" },
    { field: "bronze" },
    { field: "total" },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      width: 170,
      sortingOrder: ["desc", "asc", null],
    };
  }, []);

  const { data, loading } = useFetchJson<IOlympicData>(
    "https://www.ag-grid.com/example-assets/olympic-winners.json",
  );

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={gridStyle}>
          <AgGridReact<IOlympicData>
            rowData={data}
            loading={loading}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Sorting Order and Animation](https://www.ag-grid.com/examples/row-sorting/sorting-order-and-animation/reactFunctionalTs)

## Absolute Sorting

Absolute Sorting enables sorting numeric values based on their magnitude, ignoring their sign. This can be used to rank values by their size ignoring if a value is positive or negative.

In the following example, the column `rankingChange` uses absolute sorting:

```jsx
const [columnDefs, setColumnDefs] = useState([
    // ... other columns
    {
        field: 'rankingChange',
        sort: { direction: 'asc', type: 'absolute' },
        sortingOrder: [
            { direction: 'asc', type: 'absolute' },
            { direction: 'desc', type: 'absolute' },
            null,
        ],
    },
]);

<AgGridReact columnDefs={columnDefs} />
```

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sort` | `SortDirection \| SortDef` |  |  | Set the default sort. |
| `sortingOrder` | `(SortDirection \| SortDef)[]` |  |  | An array defining the order in which sorting occurs (if sorting is enabled). Defaults: - `['asc', 'desc', null]` if no sort type is specified, - `[{ type: 'absolute', direction: 'asc', }, { type: 'absolute', direction: 'desc' }, null]` if 'sort' or 'initialSort' have type 'absolute' |

#### Absolute Value Sorting

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
import { any } from "./interfaces";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [ClientSideRowModelModule];

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>();
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "athlete", minWidth: 150 },
    { field: "year", maxWidth: 90 },
    {
      field: "rankingChange",
      sort: { direction: "asc", type: "absolute" },
      sortingOrder: [
        { direction: "asc", type: "absolute" },
        { direction: "desc", type: "absolute" },
        null,
      ],
    },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      flex: 1,
      minWidth: 100,
    };
  }, []);

  const onGridReady = useCallback((params: GridReadyEvent) => {
    fetch("https://www.ag-grid.com/example-assets/small-olympic-winners.json")
      .then((resp) => resp.json())
      .then((data: any[]) =>
        setRowData(
          data.map((item) => {
            return {
              ...item,
              rankingChange: Math.round(window.agRandom() * 10) - 5,
            };
          }),
        ),
      );
  }, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={gridStyle}>
          <AgGridReact
            rowData={rowData}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
            onGridReady={onGridReady}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Absolute Value Sorting](https://www.ag-grid.com/examples/row-sorting/absolute-sorting/reactFunctionalTs)

## Sorting API

> **Note**
>
> The sort state can be saved and restored as part of [Grid State](https://www.ag-grid.com/react-data-grid/grid-state/).

What sorting is applied is controlled via [Column State](https://www.ag-grid.com/react-data-grid/column-state/). The below examples uses the Column State API to control column sorting.

#### Sorting API

```tsx
("use client");

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import "./styles.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  ColumnApiModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  NumberFilterModule,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";
import { useFetchJson } from "./useFetchJson";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [
  TextFilterModule,
  NumberFilterModule,
  ClientSideRowModelModule,
  ColumnApiModule,
];

let savedSort: any;

const GridExample = () => {
  const gridRef = useRef<AgGridReact<IOlympicData>>(null);
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);

  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "athlete" },
    { field: "age", width: 90 },
    { field: "country" },
    { field: "sport" },
    { field: "year", width: 90 },
    { field: "date" },
    { field: "gold" },
    { field: "silver" },
    { field: "bronze" },
    { field: "total" },
  ]);

  const { data, loading } = useFetchJson<IOlympicData>(
    "https://www.ag-grid.com/example-assets/olympic-winners.json",
  );

  const sortByAthleteAsc = useCallback(() => {
    gridRef.current!.api.applyColumnState({
      state: [{ colId: "athlete", sort: "asc" }],
      defaultState: { sort: null },
    });
  }, []);

  const sortByAthleteDesc = useCallback(() => {
    gridRef.current!.api.applyColumnState({
      state: [{ colId: "athlete", sort: "desc" }],
      defaultState: { sort: null },
    });
  }, []);

  const sortByCountryThenSport = useCallback(() => {
    gridRef.current!.api.applyColumnState({
      state: [
        { colId: "country", sort: "asc", sortIndex: 0 },
        { colId: "sport", sort: "asc", sortIndex: 1 },
      ],
      defaultState: { sort: null },
    });
  }, []);

  const sortBySportThenCountry = useCallback(() => {
    gridRef.current!.api.applyColumnState({
      state: [
        { colId: "country", sort: "asc", sortIndex: 1 },
        { colId: "sport", sort: "asc", sortIndex: 0 },
      ],
      defaultState: { sort: null },
    });
  }, []);

  const clearSort = useCallback(() => {
    gridRef.current!.api.applyColumnState({
      defaultState: { sort: null },
    });
  }, []);

  const saveSort = useCallback(() => {
    const colState = gridRef.current!.api.getColumnState();
    const sortState = colState
      .filter(function (s) {
        return s.sort != null;
      })
      .map(function (s) {
        return { colId: s.colId, sort: s.sort, sortIndex: s.sortIndex };
      });
    savedSort = sortState;
    console.log("saved sort", sortState);
  }, []);

  const restoreFromSave = useCallback(() => {
    gridRef.current!.api.applyColumnState({
      state: savedSort,
      defaultState: { sort: null },
    });
  }, [savedSort]);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div className="example-wrapper">
          <div style={{ marginBottom: "1rem" }}>
            <div>
              <button onClick={sortByAthleteAsc}>Athlete Ascending</button>
              <button onClick={sortByAthleteDesc}>Athlete Descending</button>
              <button onClick={sortByCountryThenSport}>
                Country, then Sport
              </button>
              <button onClick={sortBySportThenCountry}>
                Sport, then Country
              </button>
            </div>
            <div style={{ marginTop: "0.25rem" }}>
              <button onClick={clearSort}>Clear Sort</button>
              <button onClick={saveSort}>Save Sort</button>
              <button onClick={restoreFromSave}>Restore from Save</button>
            </div>
          </div>

          <div style={gridStyle}>
            <AgGridReact<IOlympicData>
              ref={gridRef}
              rowData={data}
              loading={loading}
              columnDefs={columnDefs}
            />
          </div>
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Sorting API](https://www.ag-grid.com/examples/row-sorting/sorting-api/reactFunctionalTs)

## Locale-specific Sort

By default, sorting is not locale-specific and strings are compared using their Unicode code point order. There is no language awareness and no locale rules are applied. If you need to make your sort locale-specific you can configure this by setting the grid option `accentedSort = true`.

> **Note**
>
> Locale-specific sort is slower than default sort which may be noticeable when sorting a large number of rows.

Toggle the buttons in the following example to see the difference between default sorting and locale-aware sorting. Note that with locale-aware sorting, the order is `a à b c` instead of the default Unicode order of `a b c à`.

#### Locale Aware Sort

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import "./styles.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [ClientSideRowModelModule];

const GridExample = () => {
  const gridRef = useRef<AgGridReact>(null);
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>(
    [..."bàac"].map((x) => ({ letter: x })),
  );
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { headerName: "Locale-specific Sort", field: "letter", sort: "asc" },
  ]);

  const applyLocale = useCallback(() => {
    gridRef.current!.api.updateGridOptions({
      accentedSort: true,
      columnDefs: [
        { field: "letter", sort: "asc", headerName: "Locale-specific Sort" },
      ],
    });
  }, []);

  const applyDefault = useCallback(() => {
    gridRef.current!.api.updateGridOptions({
      accentedSort: false,
      columnDefs: [
        { field: "letter", sort: "asc", headerName: "Default Sort" },
      ],
    });
  }, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div className="test-container">
          <div className="test-header">
            <button onClick={applyLocale}>Locale-specific Sort</button>
            <button onClick={applyDefault}>Default Sort</button>
          </div>

          <div style={gridStyle} className="test-grid">
            <AgGridReact
              ref={gridRef}
              rowData={rowData}
              columnDefs={columnDefs}
              accentedSort={true}
            />
          </div>
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Locale Aware Sort](https://www.ag-grid.com/examples/row-sorting/locale-aware-sort/reactFunctionalTs)

## Post-Sort

It is also possible to perform some post-sorting if you require additional control over the sorted rows.

This is provided via the `postSortRows` grid callback function as shown below:

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `postSortRows` | `PostSortRows` |  |  | Callback to perform additional sorting after the grid has sorted the rows. When configured, `deltaSort` is ignored. |

```jsx
const postSortRows = params => {
    let rowNodes = params.nodes;
    // here we put Ireland rows on top while preserving the sort order
    let nextInsertPos = 0;
    for (let i = 0; i < rowNodes.length; i++) {
        const country = rowNodes[i].data.country;
        if (country === 'Ireland') {
            rowNodes.splice(nextInsertPos, 0, rowNodes.splice(i, 1)[0]);
            nextInsertPos++;
        }
    }
};

<AgGridReact postSortRows={postSortRows} />
```

The following example uses this configuration to perform a post-sort on the rows. The custom function puts rows with Ireland at the top always.

#### Post Sort

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  ModuleRegistry,
  PostSortRows,
  PostSortRowsParams,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";
import { useFetchJson } from "./useFetchJson";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [ClientSideRowModelModule];

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);

  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "athlete" },
    { field: "age", width: 100 },
    { field: "country", sort: "asc" },
    { field: "year" },
    { field: "date" },
    { field: "sport" },
    { field: "gold" },
    { field: "silver" },
    { field: "bronze" },
    { field: "total" },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      width: 170,
    };
  }, []);
  const postSortRows = useCallback(
    (params: PostSortRowsParams<IOlympicData>) => {
      const rowNodes = params.nodes;
      // here we put Ireland rows on top while preserving the sort order
      let nextInsertPos = 0;
      for (let i = 0; i < rowNodes.length; i++) {
        const country = rowNodes[i].data
          ? rowNodes[i].data!.country
          : undefined;
        if (country === "Ireland") {
          rowNodes.splice(nextInsertPos, 0, rowNodes.splice(i, 1)[0]);
          nextInsertPos++;
        }
      }
    },
    [],
  );

  const { data, loading } = useFetchJson<IOlympicData>(
    "https://www.ag-grid.com/example-assets/olympic-winners.json",
  );

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={gridStyle}>
          <AgGridReact<IOlympicData>
            rowData={data}
            loading={loading}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
            postSortRows={postSortRows}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Post Sort](https://www.ag-grid.com/examples/row-sorting/post-sort/reactFunctionalTs)
