Reputation: 105
I need to render a styled div conditionally by a given string stored in Object.
I pass the data object throw props and convert it by this function convertOrdersRows
.
but it gives me that error TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' | property '_context' -> object with constructor 'Object'
const orderColumns = [
{ field: "id", headerName: "ID", width: 120 },
{ field: "date", headerName: "Date", width: 140 },
{ field: "customerName", headerName: "Customer Name", width: 190 },
{ field: "products", headerName: "Products", width: 150 },
{ field: "price", headerName: "Price", width: 90 },
{ field: "status", headerName: "Status", width: 120 },
];
const productColumns = [];
const convertToNormalDate = (date) => {
const newDate = new Date(date);
const year = newDate.getFullYear();
let month = newDate.getMonth() + 1;
let dt = newDate.getDate();
if (dt < 10) {
dt = "0" + dt;
}
if (month < 10) {
month = "0" + month;
}
return `${dt}/${month}/${year}`;
};
const convertStatusToIcon = (status) => {
let statusIcon;
switch (status) {
case "Canceled":
return (statusIcon = <Status label="Canceled" canceled />);
case "Pending":
return (statusIcon = <Status label="Pending" pending />);
case "Deliverd":
return (statusIcon = <Status label="Deliverd" deliverd />);
default:
status = <Status label="..." />;
}
return statusIcon;
};
const convertOrdersRows = (rows) => {
let data = [...rows];
return data.map((value) => {
let convertedRow = { ...value };
convertedRow.date = convertToNormalDate(convertedRow.date);
convertedRow.status = convertStatusToIcon(convertedRow.status);
convertedRow.price = `$ ${convertedRow.price}`;
return convertedRow;
});
};
const DataGrid = (props) => {
const classes = useStyles();
const { orders, products, data } = props;
const columns = orders ? orderColumns : products ? productColumns : [];
const rows = convertOrdersRows(data);
console.log(rows);
return (
<MuiDataGrid
rows={rows}
columns={columns}
checkboxSelection
autoPageSize
{...props}
/>
);
};
export default DataGrid;
Upvotes: 3
Views: 3171
Reputation: 105
Remove convertOrdersRows
and use the renderCell
prop instead as it has access to all cells throw params in the column so you can put any logic you want.
const orderColumns = [
{ field: "id", headerName: "ID", width: 120 },
{
field: "date",
headerName: "Date",
width: 140,
renderCell: (params) => convertToNormalDate(params.value),
},
{ field: "customerName", headerName: "Customer Name", width: 190 },
{ field: "products", headerName: "Products", width: 150 },
{
field: "price",
headerName: "Price",
width: 100,
renderCell: (params) => `$ ${params.value}`,
},
{
field: "status",
headerName: "Status",
width: 120,
renderCell: (params) => convertStatusToIcon(params.value),
},
];
Upvotes: 6