I have values I want to display in an AntD table. I want them to be sortable, but also formatted with commas, like "1,000". Ideally I would store them in React state as integers, and then format them as strings with commas upon display, but I haven't found a way in AntD tables to do this conversion last minute. Here's an example column JSX element displaying unformatted but sortable integers:
<Column
title="Population"
dataIndex="population"
key="population"
sorter={(a, b) => a.population - b.population}
/>
I have tried converting all my state to formatted strings, and then the table displays them nicely, but the sorting is messed up. I thought localeCompare with numeric = True would fix this, but it doesn't.
With this input:
let arr = ['999', '1,000', '1,001'];
console.log(
arr.sort((a, b) =>
a.localeCompare(b, undefined, {
numeric: true,
ignorePunctuation: true,
})
)
);
I expect the input to be sorted numerically, but it isn't. Perhaps I misunderstand how localeCompare() works. This is the result:
[ "1,000", "1,001", "999" ]
So I have two questions, and answering either one would fix my problem:
I think the best approach in your case would be to use the render property of the Column.
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Table } from "antd";
const { Column } = Table;
const data = [
{
key: "1",
name: "John Brown",
salary: 1000
},
{
key: "2",
name: "Jim Green",
salary: 2000
},
{
key: "3",
name: "Joe Black",
salary: 999
},
{
key: "4",
name: "Jim Red",
salary: 1001
}
];
ReactDOM.render(
<Table dataSource={data}>
<Column title="Name" dataIndex="name" key="name" />
<Column
title="Salary"
dataIndex="salary"
key="salary"
sorter={(a, b) => a.salary - b.salary}
render={(value) => {
return "$" + value.toLocaleString("en");
}}
/>
</Table>,
document.getElementById("container")
);