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
export default ({ columnOrder, data }: IProps) => { const [orderedColumn, setOrderedColumn] = useState<ColumnsType<ISomeTableColumns>>(columns); useEffect(() => { console.log('columnOrder', columnOrder); const sortArray = columns.sort((a, b) => { return ( columnOrder.findIndex((x) => x.text === a.title) - columnOrder.findIndex((x) => x.text === b.title) ); }); if (sortArray) { setOrderedColumn(sortArray); } }, [columnOrder]); return <> <Table columns={orderedColumn} dataSource={data} bordered size="middle" scroll={{ x: 'calc(700px + 50%)' }} /> <h2>Value Of ordered Columns</h2> <div>{JSON.stringify(orderedColumn)}</div> </> };
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
useEffect(() => { console.log('columnOrder', columnOrder); columns.sort((a, b) => { return ( columnOrder.findIndex((x) => x.text === a.title) - columnOrder.findIndex((x) => x.text === b.title) ); }); if (columns) { setOrderedColumn([...columns]); } }, [columnOrder, columns]);