import { Input, Table } from '@mantine/core'; import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'; import { useMemo, useState } from 'react'; import styles from './CustomTable.module.scss' // Sample data type DataType = { id: number, name: string, age: number } // Define columns const columns: ColumnDef[] = [ { accessorKey: 'name', header: 'Name', cell: (info) => info.getValue(), maxSize: Number.MAX_SAFE_INTEGER, }, { accessorKey: 'age', header: 'Age', cell: (info) => info.getValue(), }, ]; const CustomTable = () => { const [data, setData] = useState([ { id: 1, name: 'John Doe', age: 25 }, { id: 2, name: 'Jane Smith', age: 30 }, { id: 3, name: 'Sam Green', age: 22 }, ]); const [editingCell, setEditingCell] = useState({ rowIndex: null, columnId: null }); const tableColumns = useMemo[]>(() => columns, []); const table = useReactTable({ data, columns: tableColumns, getCoreRowModel: getCoreRowModel(), columnResizeMode: "onChange", }); // Function to handle cell edit const handleEditCell = ( rowIndex: number, columnId: keyof DataType, value: DataType[keyof DataType] ) => { const updatedData = [...data]; updatedData[rowIndex][columnId] = value; setData(updatedData); //setEditingCell({ rowIndex: null, columnId: null }); }; return ( {table.getHeaderGroups().map(headerGroup => ( {headerGroup.headers.map((header) => ( {flexRender(header.column.columnDef.header, header.getContext())}
))}
))}
{table.getRowModel().rows.map((row, rowIndex) => ( {row.getVisibleCells().map(cell => { const isEditing = editingCell.rowIndex === rowIndex && editingCell.columnId === cell.column.id; return ( setEditingCell({ rowIndex, columnId: cell.column.id })} style={{ width: cell.column.getSize() }} className={styles.td} > {isEditing ? ( handleEditCell(rowIndex, cell.column.id, e.target.value)} onBlur={() => setEditingCell({ rowIndex: null, columnId: null })} autoFocus /> ) : ( flexRender(cell.column.columnDef.cell, cell.getContext()) )} ); })} ))}
); }; export default CustomTable;