I am working on a react app and I am using the MUI Datagrid to display some data. I have used a rendercell to add an edit icon which I would like to open a pop up modal. Below is the column.
export const someColumn = [
{
field: "price",
headerName: "Price",
flex: 1,
cellClassName: "name-column--cell",
},
{
field: "editPrice",
headerName: "Edit Price",
flex: 1,
editable: false,
renderCell: (params) => {
return (
<FiEdit onClick={() => alert(params.row.price)} /> //I want to open modal with the ID as a parameter} className='cursor-pointer' />
);
},
},
];
In the component that has the Datagrid, I have the openModal function that should open the modal.
const openModal = () => {
setShowModal(true);
}
This is my Datagrid
<DataGrid
autoHeight
rows={someArray}
columns={someColumn}
slots={{ toolbar: CustomToolbar }}
/>;
How can I get the button to open up the modal? Please help.
Thanks.
According to documentation:
The renderCell property is a function that returns a React node, not a React component.
If you want to use React hooks inside your renderer, you should wrap them inside a component.
So you can create a custom component that renders both the button and the modal, and use it in the renderCell
prop of the column.
For example:
// Create a custom component that renders the button and the modal
const OpenModalButton = ({ row }) => {
const [open, setOpen] = React.useState(false);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<>
<Button onClick={handleOpen}>{row.col2}</Button>
<BasicModal
open={open}
onOpen={handleOpen}
onClose={handleClose}
row={row}
/>
</>
);
};
const columns = [
{ field: "id", hide: true },
{ field: "col1", headerName: "Column 1", width: 150 },
{
field: "col2",
headerName: "Column 2",
width: 150,
renderCell: OpenModalButton // Use the custom component here
}
];
You can see the whole example here.