Creating Editable Cells in React TanStack Table
Make table cells editable by implementing a controlled input component within a cell renderer, handling state updates to reflect changes.
import { useState } from 'react';
Import useState hook from React for managing cell value state.
const TableCell = ({ getValue, row, column, table }) => {
const initialValue = getValue();
const [value, setValue] = useState(initialValue);
useEffect(() => {
setValue(initialValue);
}, [initialValue]);
const onBlur = () => {
table.options.meta?.updateData(row.index, column.id, value);
};
return (
<input
value={value}
onChange={e => setValue(e.target.value)}
onBlur={onBlur}
/>
);
};
Defines a TableCell component that includes an input element. The component uses the useState and useEffect hooks to manage and reset its state based on the initialValue obtained from the cell's getValue function. The onBlur handler updates the table's data through the updateData function stored in table.options.meta.
const columns = [
columnHelper.accessor('studentId', {
header: 'Student ID',
cell: TableCell,
meta: { type: 'number' },
}),
columnHelper.accessor('name', {
header: 'Full Name',
cell: TableCell,
meta: { type: 'text' },
}),
// Add other columns as needed
];
Configures columns for the React Table by setting the TableCell component as the renderer for cells within the columns. It includes metadata indicating the type of data each column represents.
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
meta: {
editedRows,
setEditedRows,
updateData: (rowIndex, columnId, value) => {
// Logic to update the data source based on input changes
},
},
});
Initializes the table using the useReactTable hook from TanStack Table library, incorporating the data, columns, and a meta object that includes functions for handling row editing and data updates.