Reputation: 1
I want to add buttons in each row of the material-ui data grid... But when I'm trying to do so, I see the output as follows (rather than the button it shows something like [object Object]. enter image description here
Below is my code:
import { DataGrid } from "@mui/x-data-grid";
import React, { useState } from "react";
function App() {
const columns = [
{ field: "id", headerName: "ID", width: 70 },
{ field: "firstName", headerName: "First name", width: 130 },
{ field: "lastName", headerName: "Last name", width: 130 },
{
field: "age",
headerName: "Age",
type: "number",
width: 90,
},
{
field: "fullName",
headerName: "Full name",
description: "This column has a value getter and is not sortable.",
sortable: false,
width: 160,
valueGetter: (params) =>
`${params.getValue(params.id, "firstName") || ""} ${
params.getValue(params.id, "lastName") || ""
}`,
},
{
field: "click",
headerName: "Click",
type: <button />, /*this field stores the buttons*/
width: 90,
},
];
const [rows, setRows] = useState([
{
id: 1,
lastName: "Snow",
firstName: "<a>hello</a>",
age: 35,
click: <button>Hello</button>, /*given a button to first row*/
},
{ id: 2, lastName: "Lannister", firstName: "Cersei", age: 42 },
{ id: 3, lastName: "Lannister", firstName: "Jaime", age: 45 },
{ id: 4, lastName: "Stark", firstName: "Arya", age: 16 },
{ id: 5, lastName: "Targaryen", firstName: "Daenerys", age: null },
{ id: 6, lastName: "Melisandre", firstName: null, age: 150 },
{ id: 7, lastName: "Clifford", firstName: "Ferrara", age: 44 },
{ id: 8, lastName: "Frances", firstName: "Rossini", age: 36 },
{ id: 9, lastName: "Roxie", firstName: "Harvey", age: 65 },
]);
// setRows(
// setRows(rows);
// );
const [count, setCount] = useState(0);
const [arr, setArr] = useState([1, 2, 3]);
return (
<>
<p>you pressed {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
<div style={{ height: 400, width: "50%" }}>
<DataGrid
rows={rows}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection
/>
</div>
<table>
{arr.map((n) => (
<tr>${n}</tr>
))}
</table>
<button
onClick={(e) => {
e.preventDefault();
arr.push(4);
console.log(arr);
var t = [...rows, { id: 3 }];
// rows.push({ lastName: "hello" });
// setRows(t);
setRows(t);
console.log(rows);
// document.title = arr;
setArr(arr);
}}
>
add
</button>
</>
);
}
export default App;
Also, after the button is inserted, how can I reference the current index or id of the row inside the button, suppose if at every click of button I need to show an alert which displays the information such as id and firstname for that row... how can i do that?
Upvotes: 4
Views: 7618
Reputation: 685
use render cell:
{
field: "click",
headerName: "Click",
width: 90,
renderCell: (params) => {
// you will find row info in params
<button>Click</button>
}
},
Upvotes: 8