---
title: Sort Matrix Rows
product: Form Library
description: Learn how to enable sorting in a SurveyJS Dynamic Matrix and Multi-Select Matrix. This demo for JavaScript shows sortable column headers, a sort bar, and sorting by multiple fields while preserving the original data order.
framework: React
source: https://surveyjs.io/form-library/examples/sorting-in-matrices/reactjs
index: https://surveyjs.io/form-library/examples/overview.md
---

# Sort Matrix Rows (React)

Sorting lets respondents arrange matrix rows by column values without changing the original data order. This demo displays 30 orders in a [Dynamic Matrix](https://surveyjs.io/form-library/documentation/api-reference/dynamic-matrix-table-question-model) or [Multi-Select Matrix](https://surveyjs.io/form-library/documentation/api-reference/matrix-table-with-dropdown-list). Click a column header to apply, change, or clear sorting, or use the **Sort by** bar above the matrix to select fields and their sorting directions. Click **Add sort level** (+) to sort by multiple fields. The first field determines the primary order. Each subsequent field sorts entries within the order established by the preceding field. Use the action in the matrix title to switch between the Dynamic Matrix and Multi-Select Matrix.

> Sorting is available in SurveyJS Form Library v3.2.4 and later.

## Enable Sorting

Set the matrix's [`allowSort`](/form-library/documentation/api-reference/dynamic-matrix-table-question-model#allowSort) property to `true` to enable sorting in the UI. To prevent respondents from sorting by a column, set that column's [`allowSort`](/form-library/documentation/api-reference/multi-select-matrix-column-values#allowSort) property to `false`.

The [`showSortBar`](/form-library/documentation/api-reference/dynamic-matrix-table-question-model#showSortBar) property controls when the sort bar appears. When the property is set to `"auto"` (by default), the bar appears whenever column headers cannot be used for sorting, including on mobile devices. This demo sets it to `"always"` so that respondents can use either the bar or column headers.

## Sort by Multiple Fields

Set [`maxSortLevel`](/form-library/documentation/api-reference/dynamic-matrix-table-question-model#maxSortLevel) to a value greater than `1` to let respondents add sorting levels. This demo allows respondents to sort by up to three fields.

Respondents can use the sort bar to select multiple fields or hold Shift, Ctrl, or Cmd while clicking a column header to add a sorting level.

## Sort in Code

You can set the initial sort order in the survey JSON using the [`sortCriteria`](/form-library/documentation/api-reference/dynamic-matrix-table-question-model#sortCriteria) property. The configuration below sorts statuses from Z to A, with the largest totals first within each status group:

```json
"sortCriteria": [
  { "field": "status", "direction": "desc" },
  { "field": "total", "direction": "desc" }
]
```

The `sortCriteria` array also reflects the current sort order, including changes made by respondents.

To change the sort order at runtime, use the [`sort()`](/form-library/documentation/api-reference/dynamic-matrix-table-question-model#sort) method. It supports two signatures:

- `sort(field: string, direction?: "asc" | "desc", append?: boolean)`\
Sorts rows by the specified column. By default, the call replaces existing criteria. Set `append` to `true` to add another sorting level or update the direction of a field already included in the sort.

- `sort(criteria: Array<{ field: string, direction?: "asc" | "desc" }>)`\
Replaces existing criteria with an array of objects in the same format as `sortCriteria`. Criteria are applied in array order.

The following examples apply the same sort order using either signature:

```js
const matrix = survey.getQuestionByName("dynamicOrders");
matrix.sort("status", "desc");
matrix.sort("total", "desc", true);

// Or set both sorting levels in one call:
matrix.sort([
  { field: "status", direction: "desc" },
  { field: "total", direction: "desc" }
]);
```

To return to the original display order, call the [`clearSort()`](/form-library/documentation/api-reference/dynamic-matrix-table-question-model#clearSort) method:

```js
matrix.clearSort();
```

The following additional rules apply to sorting:

- When respondents sort rows, their display order changes, but their order in the matrix's `value` stays the same.
- The `allowSort` and `maxSortLevel` settings apply to sorting in the UI and do not limit sorting in code.

## See Also

[Demo: Sorting in Dynamic Panel](/form-library/examples/sorting-in-dynamic-panel/ (linkStyle))

[Demo: Paging in Matrices](/form-library/examples/paging-in-matrices/ (linkStyle))

## Files

### `public/index.html`

```html
<link href="https://fonts.googleapis.com/css?family=Open%20Sans:400,600&display=swap" rel="stylesheet">
<div id="surveyElement" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; min-height: 100%; height:100%"></div>
```

### `src/SurveyComponent.jsx`

```js
import React from "react";
import { Model } from "survey-core";
import { Survey } from "survey-react-ui";
import "survey-core/survey-core.min.css";
import "./index.css";
import { json } from "./json";

function SurveyComponent() {
    const survey = new Model(json);
    survey.onComplete.add((sender, options) => {
        console.log(JSON.stringify(sender.data, null, 3));
    });
    const orders = [
      { id: 1001, customer: "Bob Brown", product: "Mouse", quantity: 4, price: 39, status: "shipped" },
      { id: 1002, customer: "Grace Smith", product: "Laptop", quantity: 1, price: 1290, status: "delivered" },
      { id: 1003, customer: "Quinn Smith", product: "USB-C cable", quantity: 2, price: 15, status: "shipped" },
      { id: 1004, customer: "Elena Tanaka", product: "Monitor", quantity: 1, price: 340, status: "shipped" },
      { id: 1005, customer: "Bob Rossi", product: "Monitor", quantity: 5, price: 340, status: "shipped" },
      { id: 1006, customer: "Liam Garcia", product: "Laptop", quantity: 5, price: 1290, status: "shipped" },
      { id: 1007, customer: "Sven Chen", product: "USB-C cable", quantity: 5, price: 15, status: "shipped" },
      { id: 1008, customer: "Rosa Larsen", product: "Desk lamp", quantity: 2, price: 45, status: "delivered" },
      { id: 1009, customer: "Noah Novak", product: "Mouse", quantity: 3, price: 39, status: "delivered" },
      { id: 1010, customer: "Olga Petrova", product: "Webcam", quantity: 2, price: 89, status: "processing" },
      { id: 1011, customer: "Ines Tanaka", product: "Laptop", quantity: 2, price: 1290, status: "new" },
      { id: 1012, customer: "Tara Silva", product: "Docking station", quantity: 3, price: 219, status: "cancelled" },
      { id: 1013, customer: "Liam Kowalski", product: "Monitor", quantity: 1, price: 340, status: "cancelled" },
      { id: 1014, customer: "Pablo Ivanova", product: "Keyboard", quantity: 4, price: 79, status: "cancelled" },
      { id: 1015, customer: "Noah Haddad", product: "Docking station", quantity: 1, price: 219, status: "shipped" },
      { id: 1016, customer: "Ann Silva", product: "Monitor", quantity: 2, price: 340, status: "new" },
      { id: 1017, customer: "Grace Müller", product: "Office chair", quantity: 2, price: 410, status: "delivered" },
      { id: 1018, customer: "Elena Silva", product: "Webcam", quantity: 2, price: 89, status: "processing" },
      { id: 1019, customer: "Dmitri Okafor", product: "Office chair", quantity: 3, price: 410, status: "new" },
      { id: 1020, customer: "Mei Brown", product: "USB-C cable", quantity: 3, price: 15, status: "processing" },
      { id: 1021, customer: "Sofia Martin", product: "Headset", quantity: 2, price: 119, status: "new" },
      { id: 1022, customer: "Lucas Chen", product: "Laptop", quantity: 1, price: 1290, status: "processing" },
      { id: 1023, customer: "Amira Hassan", product: "Desk lamp", quantity: 4, price: 45, status: "shipped" },
      { id: 1024, customer: "Oscar Silva", product: "Keyboard", quantity: 3, price: 79, status: "delivered" },
      { id: 1025, customer: "Hana Novak", product: "Monitor", quantity: 2, price: 340, status: "new" },
      { id: 1026, customer: "Leo Rossi", product: "Webcam", quantity: 1, price: 89, status: "processing" },
      { id: 1027, customer: "Maya Garcia", product: "Office chair", quantity: 3, price: 410, status: "shipped" },
      { id: 1028, customer: "Ivan Larsen", product: "Docking station", quantity: 2, price: 219, status: "delivered" },
      { id: 1029, customer: "Nina Tanaka", product: "Mouse", quantity: 5, price: 39, status: "cancelled" },
      { id: 1030, customer: "Adam Kowalski", product: "USB-C cable", quantity: 4, price: 15, status: "processing" }
    ];
    
    // Initialize totals so all orders can be sorted by this field.
    orders.forEach(order => {
      order.total = order.quantity * order.price;
    });
    
    let nextOrderId = Math.max(...orders.map(order => order.id)) + 1;
    survey.onMatrixRowAdded.add((_, options) => {
      if (options.question.name === "dynamicOrders") {
        options.row.getQuestionByColumnName("id").value = nextOrderId++;
      }
    });
    survey.onGetQuestionTitleActions.add((_, options) => {
      const name = options.question.name;
      if (name !== "dynamicOrders" && name !== "fixedOrders") return;
    
      const isDynamic = name === "dynamicOrders";
      options.actions.push({
        id: "switch-matrix-type",
        title: isDynamic ? "Switch to Multi-Select Matrix" : "Switch to Dynamic Matrix",
        action: () => {
          survey.currentPageNo = isDynamic ? 1 : 0;
        }
      });
    });
    
    survey.getQuestionByName("fixedOrders").rows = orders.map(order => String(order.id));
    
    const fixedOrders = {};
    orders.forEach(order => {
      fixedOrders[order.id] = {
        customer: order.customer,
        product: order.product,
        quantity: order.quantity,
        price: order.price,
        total: order.total,
        status: order.status
      };
    });
    
    survey.data = {
      dynamicOrders: orders,
      fixedOrders: fixedOrders
    };
    
    return (<Survey model={survey} />);
}

export default SurveyComponent;
```

### `src/index.css`

```css
/* You can add your custom CSS here. */
```

### `src/index.js`

```js
import React from "react";
import { createRoot } from "react-dom/client";
import SurveyComponent from "./SurveyComponent";

const root = createRoot(document.getElementById("surveyElement"));
root.render(<SurveyComponent />);
```

### `src/json.js`

```js
export const json = {
  "showNavigationButtons": false,
  "pages": [
    {
      "name": "dynamic-matrix",
      "elements": [
        {
          "type": "matrixdynamic",
          "name": "dynamicOrders",
          "title": "Orders (Dynamic Matrix)",
          "allowSort": true,
          "showSortBar": "always",
          "maxSortLevel": 3,
          "sortCriteria": [
            { "field": "status", "direction": "desc" },
            { "field": "total", "direction": "desc" }
          ],
          "addRowText": "Add order",
          "columns": [
            {
              "name": "id",
              "title": "Order #",
              "cellType": "text",
              "inputType": "number",
              "readOnly": true,
              "width": "70px"
            },
            {
              "name": "customer",
              "title": "Customer",
              "cellType": "text",
              "isRequired": true
            },
            {
              "name": "product",
              "title": "Product",
              "choices": [
                "Laptop",
                "Monitor",
                "Keyboard",
                "Mouse",
                "Headset",
                "Docking station",
                "Webcam",
                "Desk lamp",
                "Office chair",
                "USB-C cable"
              ]
            },
            {
              "name": "quantity",
              "title": "Qty",
              "cellType": "text",
              "inputType": "number",
              "min": 1,
              "width": "80px"
            },
            {
              "name": "price",
              "title": "Unit price ($)",
              "cellType": "text",
              "inputType": "number",
              "min": 0,
              "width": "110px"
            },
            {
              "name": "total",
              "title": "Total",
              "cellType": "expression",
              "expression": "{row.quantity} * {row.price}",
              "displayStyle": "currency"
            },
            {
              "name": "status",
              "title": "Status",
              "choices": [
                { "value": "new", "text": "New" },
                { "value": "processing", "text": "Processing" },
                { "value": "shipped", "text": "Shipped" },
                { "value": "delivered", "text": "Delivered" },
                { "value": "cancelled", "text": "Cancelled" }
              ]
            }
          ]
        }
      ]
    },
    {
      "name": "multi-select-matrix",
      "elements": [
        {
          "type": "matrixdropdown",
          "name": "fixedOrders",
          "title": "Orders (Multi-Select Matrix)",
          "allowSort": true,
          "showSortBar": "always",
          "maxSortLevel": 3,
          "sortCriteria": [
            { "field": "status", "direction": "desc" },
            { "field": "total", "direction": "desc" }
          ],
          "columns": [
            {
              "name": "customer",
              "title": "Customer",
              "cellType": "text",
              "isRequired": true
            },
            {
              "name": "product",
              "title": "Product",
              "choices": [
                "Laptop",
                "Monitor",
                "Keyboard",
                "Mouse",
                "Headset",
                "Docking station",
                "Webcam",
                "Desk lamp",
                "Office chair",
                "USB-C cable"
              ]
            },
            {
              "name": "quantity",
              "title": "Qty",
              "cellType": "text",
              "inputType": "number",
              "min": 1,
              "width": "80px"
            },
            {
              "name": "price",
              "title": "Unit price ($)",
              "cellType": "text",
              "inputType": "number",
              "min": 0,
              "width": "110px"
            },
            {
              "name": "total",
              "title": "Total",
              "cellType": "expression",
              "expression": "{row.quantity} * {row.price}",
              "displayStyle": "currency"
            },
            {
              "name": "status",
              "title": "Status",
              "choices": [
                { "value": "new", "text": "New" },
                { "value": "processing", "text": "Processing" },
                { "value": "shipped", "text": "Shipped" },
                { "value": "delivered", "text": "Delivered" },
                { "value": "cancelled", "text": "Cancelled" }
              ]
            }
          ]
        }
      ]
    }
  ]
}
;
```

### `src/theme.js`

```js
export const themeJson = {};
```

### `package.json`

```json
{
  "dependencies": {
    "react": "latest",
    "react-dom": "latest",
    "survey-core": "latest",
    "survey-react-ui": "latest"
  },
  "devDependencies": {
    "react-scripts": "latest"
  }
}
```

## Other Frameworks

- [Angular](https://surveyjs.io/form-library/examples/sorting-in-matrices/angular.md)
- [Vue 3](https://surveyjs.io/form-library/examples/sorting-in-matrices/vue3js.md)
- [jQuery](https://surveyjs.io/form-library/examples/sorting-in-matrices/jquery.md)
- [Vanilla JS](https://surveyjs.io/form-library/examples/sorting-in-matrices/vanillajs.md)
