Skip to main content

Sorting data

Enable sorting

To enable sorting data by columns in ascending/descending order, set the sort parameter of the needed column in the columns array to true. Multiple sorting is activated by default in case sorting is set for more than one column.

In UI users can sort data by a single column clicking a column header. For multiple sorting users hold the Ctrl key and click column headers in the order they want to apply sorting. In this case the sort index appears in the column header.

The example below shows how to enable sorting for columns:

import { Grid } from "@svar-ui/react-grid";
import { getData } from "./common/data";

const { data } = getData();

const columns = [
{ id: "id", width: 50, sort: true },
{ id: "city", header: "City", width: 160, sort: true },
{ id: "email", header: "Email", width: 250, sort: true },
];

export default function Example() {
return <Grid data={data} columns={columns} />;
}

You can also use the api.exec() method and the sort-rows action to sort data programmatically. The example below shows how to sort data by the id column in the descending order at the initialization.

import { Grid } from "@svar-ui/react-grid";
import { getData } from "./common/data";

const { data } = getData();

const columns = [
{ id: "id", width: 50, sort: true },
{ id: "city", header: "City", width: 160, sort: true },
{ id: "email", header: "Email", width: 250, sort: true },
{ id: "firstName", header: "First Name", sort: true },
{ id: "lastName", header: "Last Name", sort: true },
];

const init = (api) => {
api.exec("sort-rows", { key: "id", order: "desc" });
};

export default function Example() {
return <Grid data={data} columns={columns} init={init} />;
}

Disable multiple sorting

To disable multiple sorting, you should apply the add parameter of the sort-rows action by setting its value to false and use the api.intercept() method. In this case it will be possible to sort data only by one column at a time (a user should click the required column header).

import { Grid } from "@svar-ui/react-grid";
import { getData } from "./common/data";

const { data } = getData();

const columns = [
{ id: "id", width: 50, sort: true },
{ id: "city", header: "City", width: 160, sort: true },
{ id: "email", header: "Email", width: 250, sort: true },
{ id: "firstName", header: "First Name", sort: true },
{ id: "lastName", header: "Last Name" },
];

function init(api){
api.intercept("sort-rows", (ev) => {
ev.add = false;
});
}

export default function Example() {
return <Grid data={data} columns={columns} init={init} />;
}

Related articles: