I am having trouble rerendering the columns of my table, the library i am using is ant design and I am trying to create a feature where I reorder the column of the table on demand.
I have created an example the issue here: https://replit.com/@coupacoupa/Ant-Design-column-reordering
In the example, I created a simple button that changes the order of the column which changes a div showcasing the state changed, but in the ant design table, the column doesn’t change.
Below is a snipplet of the way I change the state
JavaScript
x
29
29
1
export default ({ columnOrder, data }: IProps) => {
2
const [orderedColumn, setOrderedColumn] = useState<ColumnsType<ISomeTableColumns>>(columns);
3
4
useEffect(() => {
5
console.log('columnOrder', columnOrder);
6
const sortArray = columns.sort((a, b) => {
7
return (
8
columnOrder.findIndex((x) => x.text === a.title) -
9
columnOrder.findIndex((x) => x.text === b.title)
10
);
11
});
12
13
if (sortArray) {
14
setOrderedColumn(sortArray);
15
}
16
}, [columnOrder]);
17
18
return <>
19
<Table
20
columns={orderedColumn}
21
dataSource={data}
22
bordered
23
size="middle"
24
scroll={{ x: 'calc(700px + 50%)' }}
25
/>
26
<h2>Value Of ordered Columns</h2>
27
<div>{JSON.stringify(orderedColumn)}</div>
28
</>
29
};
Advertisement
Answer
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. But you should pass a new array into setOrderedColumn to rerender
JavaScript
1
14
14
1
useEffect(() => {
2
console.log('columnOrder', columnOrder);
3
columns.sort((a, b) => {
4
return (
5
columnOrder.findIndex((x) => x.text === a.title) -
6
columnOrder.findIndex((x) => x.text === b.title)
7
);
8
});
9
10
if (columns) {
11
setOrderedColumn([columns]);
12
}
13
}, [columnOrder, columns]);
14