6. Adding Sort and Filters
Adding Sortingβ
We will use <Table.Column/>
's sorter
prop to add sorting to the table. You just need to open src/pages/blog-posts/list.tsx
file and add the sorter
prop to the <Table.Column/>
component of the id
column:
<Table.Column
dataIndex="id"
title="Id"
sorter
/>
Now, you can sort the data by id
on the table.
If you want to add multiple sorting capabilities to the table, you can add the sorter
prop by priority.
For example, if you want to sort the data by id
first and then by name
on the table, you can add sorter
prop as below:
```tsx
<Table.Column
dataIndex="id"
title="Id"
//highlight-next-line
sorter
/>
<Table.Column
dataIndex="id"
title="Name"
//highlight-next-line
sorter={{ multiple: 1 }}
/>
```
Adding Filtersβ
We'll use <Table.Column/>
's filterDropdown
prop and the <FilterDropdown/>
component to add filters to the table.
<FilterDropdown/>
acts as a bridge between its child input and the useTable
hook, providing necessary props and handling filtering logic. To add filtering to the category
column, we'll use the <Select/>
component from Ant Design as the child input and the useSelect
hook to get necessary props like options
.
First of all, open the src/pages/blog-posts/list.tsx
file and import the following components and hooks:
```tsx
import { FilterDropdown, useSelect } from "@refinedev/antd";
import { Select } from "antd";
```
Then call the useSelect
hook with the categories
resource to fill the <Select/>
component with category options:
```tsx
const { selectProps: categorySelectProps } = useSelect({
resource: "categories",
});
```
Finally, follow the steps below:
- Add
filterDropdown
prop to the<Table.Column/>
component of thecategory
column. - Add the
<FilterDropdown/>
component as the return value of the prop. Then, pass theprops
to the<FilterDropdown/>
component. - Add the
<Select/>
component as the child of<FilterDropdown/>
component. Then, pass thecategorySelectProps
to the<Select/>
component.
<Table.Column
dataIndex={["category", "id"]}
title="category"
render={(value) => {
if (isLoading) {
return <TextField value="Loading..." />;
}
return (
<TextField
value={
categoriesData?.data.find((item) => item.id === value)
?.title
}
/>
);
}}
filterDropdown={(props) => (
<FilterDropdown {...props}>
<Select
style={{ minWidth: 200 }}
mode="multiple"
placeholder="Select Category"
{...categorySelectProps}
/>
</FilterDropdown>
)}
/>
And now, you can search and filter the data by category on the table.
For more information, check out the following documents:
Ant Design
<Table/>
documentation for thefilterDropdown
prop.<FilterDropdown/>
documentation for the<FilterDropdown/>
component.