Creating Editable Table Cells
Provide an example of how to make table cells editable, including a controlled input component for editing cell values and handling state updates.
import React, { useState } from 'react';
Imports React and the useState hook, which are necessary for managing the state in a function component.
const TableCell = ({ initialValue, onValueChange }) => {
const [value, setValue] = useState(initialValue);
const handleChange = (e) => {
setValue(e.target.value);
onValueChange(e.target.value);
};
return <input value={value} onChange={handleChange} />;
};
Defines a TableCell component that accepts an initialValue and a callback function onValueChange. It renders an input field that updates its value based on user input, and informs the parent component about the change.
const EditableTable = ({ data }) => {
const handleValueChange = (rowIndex, columnKey, newValue) => {
// Logic to update the data source with the new value
console.log(`Updated row ${rowIndex} column ${columnKey} with value ${newValue}`);
};
return (
<table>
<tbody>
{data.map((row, rowIndex) => (
<tr key={rowIndex}>
{Object.keys(row).map((key) => (
<td key={key}>
<TableCell initialValue={row[key]} onValueChange={(newValue) => handleValueChange(rowIndex, key, newValue)} />
</td>
))}
</tr>
))}
</tbody>
</table>
);
};
Creates an EditableTable component that renders a table with editable cells. It maps over the data array to produce table rows and cells, with each cell being an instance of the TableCell component. It passes each cell's initial value and a change handler that logs changes.