From 240885cf938ef7413ebadafcd7868e99fcfc3adb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A4=D1=80=D0=BE=D0=BB=D0=BE=D0=B2?= Date: Thu, 19 Aug 2021 11:40:26 +0500 Subject: [PATCH] Add autokeys --- src/components/EditableTable.jsx | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/components/EditableTable.jsx b/src/components/EditableTable.jsx index ce8003e..c867b16 100644 --- a/src/components/EditableTable.jsx +++ b/src/components/EditableTable.jsx @@ -37,6 +37,14 @@ const EditableCell = ({ ) } +const tryAddKeys = (items) => { + if(!items?.length) + return [] + if(items[0].key) + return items + return items.map((item, index) => ({...item, key: item.key ?? item.id ?? index })) +} + export const EditableTable = ({ columns, dataSource, @@ -47,11 +55,11 @@ export const EditableTable = ({ ...otherTableProps}) => { const [form] = Form.useForm() - const [data, setData] = useState(dataSource?? []) + const [data, setData] = useState(tryAddKeys(dataSource)) const [editingKey, setEditingKey] = useState('') useEffect(()=>{ - setData(dataSource??[]) + setData(tryAddKeys(dataSource)) },[dataSource]) const isEditing = (record) => record.key === editingKey @@ -168,6 +176,7 @@ export const EditableTable = ({ editing: isEditing(record), record, dataIndex: col.dataIndex ?? col.key, + key: col.key ?? col.dataIndex, input: col.input, isRequired: col.isRequired, title: col.title, @@ -180,7 +189,7 @@ export const EditableTable = ({ } const mergedColumns = [...columns.map(handleColumn), operationColumn] - + return (