Skip to main content

Sorting data

Enable sorting

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

In UI a user can sort data by a single column clicking a column header. For multiple sorting a user holds the Ctrl key and clicks column headers in the order the user wants 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 "wx-react-grid";

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 App() {
return (
<Grid data={data} columns={columns} />
);
}

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

import { Grid } from "wx-react-grid";
import { useRef } from "react";
import { getData } from "./common/data";

const { data } = getData();

let 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 },
];

export default function App() {
const api = useRef(null);

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

return (
<Grid data={data} columns={columns} api={api} 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 "wx-react-grid";
import { getData } from "./common/data";

const { data } = getData();

let 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" },
];

export default function App() {
const api = useRef(null);

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

return <Grid data={data} columns={columns} api={api} />;
}

Related articles: