I would like to edit a cell in a Datagrid by code.
The Datagrid itself has editable columns (firstName and lastName), but if you regret this change there is a column with a cancel button per row that should reset the cells of the same row to the default values.
You can make changes in several rows of the datagrid and just restore some rows, not all of them, so reseting the entire datagrid isn't an option.
How should I approach this?
Thank you in advance!
import React from "react";
import { DataGrid } from "@mui/x-data-grid";
import { Button } from "@mui/material";
export default function DataTable() {
const columns = [
{ field: 'id', headerName: 'ID' },
{ field: 'firstName', headerName: 'First name', editable: true },
{ field: 'lastName', headerName: 'Last name', editable: true },
{ field: 'cancel', headerName: 'Cancel', renderCell: (params) => <button onClick={ handleButton }/> },
];
const rows = [
{ id: 1, lastName: 'Snow', firstName: 'Jon' },
{ id: 2, lastName: 'Lannister', firstName: 'Cersei' },
{ id: 3, lastName: 'Lannister', firstName: 'Jaime' },
{ id: 4, lastName: 'Stark', firstName: 'Arya' },
{ id: 5, lastName: 'Targaryen', firstName: 'Daenerys' },
];
const handleButton = (event) => {
// CODE HERE
}
return (
<DataGrid
rows = {rows}
columns = { columns }
/>
);
}
You can use useState hook to update the table data with onCellEditCommit (is to sync data with single-cell update)and handleButton(is to reset the row) handlers defined as below.
Try like below:
import React, { useState } from "react";
import { DataGrid } from "@mui/x-data-grid";
export default function DataTable() {
const columns = [
{ field: "id", headerName: "ID" },
{
field: "firstName",
headerName: "First name",
editable: true
},
{ field: "lastName", headerName: "Last name", editable: true },
{
field: "cancel",
headerName: "Cancel",
renderCell: (params) => (
<button onClick={() => handleButton(params)}>cancel</button>
)
}
];
const rows = [
{ id: 1, lastName: "Snow", firstName: "Jon" },
{ id: 2, lastName: "Lannister", firstName: "Cersei" },
{ id: 3, lastName: "Lannister", firstName: "Jaime" },
{ id: 4, lastName: "Stark", firstName: "Arya" },
{ id: 5, lastName: "Targaryen", firstName: "Daenerys" }
];
const [data, setData] = useState(rows);
const handleButton = ({ id }) => {
setData((prevData) =>
prevData.map((item) =>
item.id === id ? { ...item, firstName: "", lastName: "" } : item
)
);
};
const onCellEditCommit = ({ id, field, value }) => {
setData((prevData) =>
prevData.map((item) =>
item.id === id ? { ...item, [field]: value } : item
)
);
};
console.log(data);
return (
<div style={{ height: 400, width: "100%" }}>
<DataGrid
rows={data}
columns={columns}
onCellEditCommit={onCellEditCommit}
/>
</div>
);
}
Working Demo