react display multi dimensional array from redux-form - reactjs

I need to display data in table with crud from redux-form with field arrays. What the best way would be to do this in Reactjs?
At the moment I am using react-table, but cant get subtable maped with parent values it just repeats the same values. Any ideas? Thanks
table sample code below for this table:
var result = _.flatMap(items, item =>
_(item.panel_group)
.map(v => ({id: item._id, inst_name:item.name, lat:item.lat, lon:item.lon, pv_name: v.name, azimuth: v.azimuth, inv_eff: v.inv_eff, losses: v.losses, system_capacity: v.system_capacity, tilt: v.tilt}))
.value()
);
const columns2 = [
{
Header: "Pv Name",
id:"pv_name",
accessor:"pv_name"
},
{
Header: "Size",
id:"size",
accessor:"system_capacity"
},
{
Header: "losses",
id: "losses",
accessor: "losses"
},
]
<div>
<ReactTable
data={items}
columns={columns}
defaultPageSize={5}
filterable
SubComponent={row => {
return (
<div style={{ padding: "20px" }}>
<ReactTable
data={result}
columns={columns2}
defaultPageSize={3}
showPagination={false}
/>
</div>
);
}}
/>
</div>
as well I tried to do like this as well result in picture :
{
Header: "Instalation Name",
id:"name",
accessor: "name"
},
{
Header: "latitude",
id: "latitude",
accessor: "lat"
},
{
Header: "longitude",
id: "longitude",
accessor: "lon"
},
{
Header: "Pv Name",
id:"pv_name",
accessor:row => {
return (
<div>
{row.panel_group.map((panel) => (
<div key={panel.id}>{panel.name} </div>
))}
</div>
)
},
},
{
Header: "Size",
id:"size",
accessor:row => {
return (
<span>
{row.panel_group.map((panel) => (
<div key={panel.id}>{panel.system_capacity}</div>
))}
</span>
)
},
},
is there any better ways to represent such data?
sample json
[
{
"_id": "59e0cbdf438488010f84968d",
"name": "hh",
"lat": 12.33,
"lon": -12.555,
"panel_group": [
{
"installation_id": "test",
"name": "name",
"system_capacity": 2,
"azimuth": 120,
"tilt": 12,
"losses": 4,
"inv_eff": 98,
"_id": "59e0cbdf438488010f84968f",
},
{
"installation_id": "test2",
"name": "name2",
"system_capacity": 1,
"azimuth": 110,
"tilt": 11,
"losses": 14,
"inv_eff": 18,
"_id": "59e0cbdf438488010f84968e"
}
],
{
"_id": "59e7798821306f001beeed19",
"name": "installation1",
"lat": 12.33,
"lon": -12.555,
"panel_group": [
{
"name": "panelgroup1",
"system_capacity": 20,
"azimuth": 120,
"tilt": 12,
"losses": 4,
"inv_eff": 98,
"_id": "59e7798821306f001beeed1b"
},
{
"name": "panelgroup2",
"system_capacity": 100,
"azimuth": 110,
"tilt": 11,
"losses": 14,
"inv_eff": 18,
"_id": "59e7798821306f001beeed1a"
}
],
}]

Related

Read array inside array into table Material UI

So i have an array of response from backend services as below (array inside an array), i try to figure it how to turn it into table but have some problem on the logic:
"data": [
{
"id": "63ad33c69acfa205d354256b",
"material": "1000000000",
"material_name": "SAMPEL",
"plant": "K111",
"type": "rm",
"current_price": 7718,
"price": []
},
{
"id": "63ad33c69acfa205d354256a",
"material": "1000000000",
"material_name": "SAMPEL",
"plant": "K109",
"type": "rm",
"current_price": 7718,
"price": []
},
{
"id": "63ad33c69acfa205d3542565",
"material": "1000000000",
"material_name": "SAMPEL",
"plant": "K103",
"type": "rm",
"current_price": 37259,
"price": [
{
"date": "januari",
"price": 37258.978184562315
},
{
"date": "februari",
"price": 37258.978184562315
},
{
"date": "maret",
"price": 37258.978184562315
},
{
"date": "april",
"price": 37258.978184562315
},
{
"date": "mei",
"price": 37258.978184562315
},
{
"date": "juni",
"price": 37258.978184562315
},
{
"date": "juli",
"price": 37258.978184562315
},
{
"date": "agustus",
"price": 37258.978184562315
},
{
"date": "september",
"price": 37258.978184562315
},
{
"date": "oktober",
"price": 37258.978184562315
},
{
"date": "november",
"price": 37258.978184562315
},
{
"date": "desember",
"price": 37258.978184562315
}
]
},
]
does it possible to turn it into table as below using material UI datagrid or similar table library?:
any help on this will be very helpful....
https://github.com/ChangeWithCode/datantable
Here I have implemented that you can have a look.
<div className="App">
<table>
<tr>
<th rowspan="2">material</th>
<th rowspan="2">material_name</th>
<th rowspan="2">plant</th>
<th rowspan="2">type</th>
<th rowspan="2">current_price</th>
<th colspan="12">Price</th>
</tr>
<tr>
<td>januari</td>
<td>februari</td>
<td>maret</td>
<td>april</td>
<td>mei</td>
<td>juni</td>
<td>juli</td>
<td>agustus</td>
<td>september</td>
<td>oktober</td>
<td>november</td>
<td>desember</td>
</tr>
{object.data.map((item) => {
return (
<tr>
<td>{item.material}</td>
<td>{item.material_name}</td>
<td>{item.plant}</td>
<td>{item.current_price}</td>
<td>{item.material_name}</td>
{item.price.map((obj) => {
return <td>{obj.price}</td>;
})}
</tr>
);
})}
</table>
</div>
The following solution using material table import MaterialTable from 'material-table';:
<MaterialTable
columns={[
{ title: 'material', field: 'material' },
{ title: 'material_name', field: 'material_name' },
{ title: 'plant', field: 'plant' },
{ title: 'type', field: 'type' },
{
title: 'current_price',
field: 'current_price',
},
{
title: 'price',
field: 'price',
render: (rowData) => (
<MaterialTable
columns={
rowData.price.length > 0
? rowData.price.map((el) => ({ title: el.date, field: 'price' }))
: [
{ title: 'januari', field: '' },
{ title: 'februari', field: '' },
{ title: 'maret', field: '' },
{ title: 'april', field: '' },
{ title: 'mei', field: '' },
{ title: 'juni', field: '' },
{ title: 'juli', field: '' },
{ title: 'agustus', field: '' },
{ title: 'september', field: '' },
{ title: 'oktober', field: '' },
{ title: 'november', field: '' },
{ title: 'desember', field: '' },
]
}
data={rowData.price}
options={{ toolbar: false }}
/>
),
},
]}
data={data}
title="Demo Title"
/>

How to get the selected values in a DataGrid with React Material UI

I'm working with a React MUI DataGrid. I need to get the values of the selected rows. At the moment, only the ids are coming through, and I get several errors throughout.
rows = data;
const columns = [
{
field: "id",
headerName: "ID",
sortable: false,
hide: true,
},
{
field: "firstName",
headerName: "First Name",
},
{
field: "lastName",
headerName: "Last Name",
},
{
field: "age",
headerName: "Age",
}
];
This is my React Hook.
const [ selection, setSelection ] = useState<GridSelectionModel>([]);
And this is the DataGrid.
<div style={{ height: 400, width: "100%" }}>
<DataGrid
rows={rows}
columns={columns}
checkboxSelection
getRowId={(row) => row.id}
onSelectionModelChange={(newSelection) => {
setSelection(newSelection);
console.log("selection", selection)
}}
{...rows}
/>
</div>
This prints the id.
<p>{selection.map((data) => data)}</p>
But, what I need, and I'm not able to figure out is:
{selection.map((data) => {
return (
<div key={data.id}>. <---ERROR
<p>{data.firstName}</p> <---ERROR
<p>{data.lastName}</p> <---ERROR
</div>
)
})}
When I do it this way, I get the following error: "Property does not exist on type 'GridRowId'."
selection will be an array of IDs instead of an array of items. You can remap the IDs back to your items, E.g,
data.json
[
{
"id": "id-001",
"firstName": "First Name 1",
"lastName": "Last Name 1",
"age": 1
},
{
"id": "id-002",
"firstName": "First Name 2",
"lastName": "Last Name 2",
"age": 2
},
{
"id": "id-003",
"firstName": "First Name 3",
"lastName": "Last Name 3",
"age": 3
},
{
"id": "id-004",
"firstName": "First Name 4",
"lastName": "Last Name 4",
"age": 4
},
{
"id": "id-005",
"firstName": "First Name 5",
"lastName": "Last Name 5",
"age": 5
}
]
App.tsx
import { useState } from "react";
import { DataGrid, GridSelectionModel } from "#mui/x-data-grid";
import data from "./data.json";
const columns = [
{
field: "id",
headerName: "ID",
sortable: false,
hide: true
},
{
field: "firstName",
headerName: "First Name"
},
{
field: "lastName",
headerName: "Last Name"
},
{
field: "age",
headerName: "Age"
}
];
// NOTE: Pulls in imported json data.
const rows = data;
export default function App() {
const [selection, setSelection] = useState<GridSelectionModel>([]);
return (
<div>
<div style={{ height: 400, width: "100%" }}>
<DataGrid
rows={rows}
columns={columns}
checkboxSelection
gridRowId={(row) => row.id}
onSelectionModelChange={setSelection}
{...rows}
/>
</div>
<div>
{selection
.map((selectedId) => data.find((item) => item.id === selectedId))
.map(({ id, firstName, lastName }) => (
<div key={id}>
<p>{firstName}</p>
<p>{lastName}</p>
</div>
))}
</div>
</div>
);
}
For those using TypeScript, adding the following allowed the accepted code above to work.
Added "GridColDef[]" type.
const columns: GridColDef[] = [
{
field: "id",
headerName: "ID",
sortable: false,
hide: true
},
{
field: "firstName",
headerName: "First Name"
},
{
field: "lastName",
headerName: "Last Name"
},
{
field: "age",
headerName: "Age"
}
];
And adding a type of "any" where I'm pulling in the data.
const rows: any = data;

React project - Material UI Data grid display nested array object in a cell

I have been trying to create a Material Data Grid to display the number of users and the roles assigned to them.
The data structure looks like:
User 1: {admin, seller}
User 2: {admin}
User 3: {admin, seller, user}
The json response from the api for the users object looks like:
users: [
{
"id": 7,
"email": "ajha#gmail.com",
"phone": "+91-9686660322",
"firstName": "Ankur",
"lastName": "Jhavery",
"avatar": "http:img.bb/123we",
"verified": false,
"createdAt": "2022-04-07T16:09:35.000Z",
"updatedAt": "2022-04-07T16:09:35.000Z",
"roles": [
{
"id": 1,
"roleName": "admin",
"userRoles": {
"createdAt": "2022-04-07T16:09:35.000Z",
"updatedAt": "2022-04-07T16:09:35.000Z",
"roleId": 1,
"userId": 7
}
},
{
"id": 2,
"roleName": "seller",
"userRoles": {
"createdAt": "2022-04-07T16:09:35.000Z",
"updatedAt": "2022-04-07T16:09:35.000Z",
"roleId": 2,
"userId": 7
}
},
{
"id": 3,
"roleName": "user",
"userRoles": {
"createdAt": "2022-04-07T16:09:35.000Z",
"updatedAt": "2022-04-07T16:09:35.000Z",
"roleId": 3,
"userId": 7
}
}
]
}
]
I am trying to render it in a React component:
const getFullName = (params) => {
return `${params.row.firstName || ''} ${params.row.lastName || ''}`;
};
const columns = [
{ field: 'id', headerName: 'Id', width: 50 },
{
field: 'fullName',
headerName: 'Full Name',
width: 150,
valueGetter: getFullName,
},
{ field: 'email', headerName: 'Email', width: 150 },
{ field: 'phone', headerName: 'Phone', width: 150 },
{ field: 'verified', headerName: 'Verified', width: 150 },
{
field: 'roles',
headerName: 'Roles',
width: 150,
valueFormatter: (params) => params.value.roleName,
type: 'string',
},
];
const Users = () => {
const [users, setUsers] = useState([]);
const getAllUsers = async () => {
try {
const response = await axios.get(
'http://localhost:8000/api/v1/admin/users'
);
if (response) {
const users = response.data.users;
setUsers(users);
}
} catch (err) {
console.log(`Error: ${err}`);
}
};
useEffect(() => {
getAllUsers();
}, []);
return (
<div className="p-5">
Users
<div className="flex flex-grow w-[60rem] h-[20rem]">
<DataGrid rows={users} columns={columns} />
</div>
</div>
);
};
export default Users;
However, the output is still showing as [Object, object]
The output that I am willing to produce for the Roles cell is to get an array of string objects which I can then display as a list using:
<ul className='flex'>
{roles.map((role, index) =>(
<li key={index}>{role}</li>
))}
</ul>
Solved it using the below code in Roles column:
{
field: 'roles',
headerName: 'Roles',
width: 150,
renderCell: (params) => (
<ul className="flex">
{params.value.map((role, index) => (
<li key={index}>{role.roleName}</li>
))}
</ul>
),
type: 'string',
},

Ant design 4 table loading not working properly

Im using my react project for ant design 4, i added table loading for loading, I have some conflict added loaded not working, anyone know how to fix that issue?
Thanks
code here
Here the stackblitz
const columns = [
{
title: "Name",
dataIndex: "name",
key: "name",
render: text => {text}
},
{
title: "Age",
dataIndex: "age",
key: "age"
},
{
title: "Address",
dataIndex: "address",
key: "address"
},
{
title: "Tags",
key: "tags",
dataIndex: "tags",
render: tags => (
<span>
{tags.map(tag => {
let color = tag.length > 5 ? "geekblue" : "green";
if (tag === "loser") {
color = "volcano";
}
return (
<Tag color={color} key={tag}>
{tag.toUpperCase()}
</Tag>
);
})}
</span>
)
},
{
title: "Action",
key: "action",
render: (text, record) => (
<span>
Invite {record.name}
<Divider type="vertical" />
Delete
</span>
)
}
];
class App extends React.Component {
state = {
data: [],
pagination: {
current: 1,
pageSize: 10
},
loading: true
};
componentDidMount() {
setTimeout(() => {
this.setState({ loading: false });
}, 1000);
}
render() {
const data = [
{
key: "1",
name: "John Brown",
age: 32,
address: "New York No. 1 Lake Park",
tags: ["nice", "developer"]
},
{
key: "2",
name: "Jim Green",
age: 42,
address: "London No. 1 Lake Park",
tags: ["loser"]
},
{
key: "3",
name: "Joe Black",
age: 32,
address: "Sidney No. 1 Lake Park",
tags: ["cool", "teacher"]
}
];
return (
<Table
columns={columns}
dataSource={data}
loading={this.state.loading}
onChange={this.handleTableChange}
/>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));

Using different font size in each row in antd react table

I have a straighforward react table by antd and I noticed all font sizes in all tables are the same.
I have different sizes in my json file as such :
{
"id": "29609-p3bse3294pj",
"size": 32,
"price": 806,
"date": "Wed Jul 31 2019 05:50:53 GMT+0300 (Turkey Standard Time)"
},
{
"id": "72738-axmupi8rnkb",
"size": 23,
"price": 370,
"date": "Sat Jul 20 2019 18:22:35 GMT+0300 (Turkey Standard Time)"
},
and I wish to render each row in respective of the size provided for the font of that row.
Just style the rendered row with Column.render property.
const dataSource = [
{
id: '29609-p3bse3294pj',
size: 32,
price: 806
},
{
id: '72738-axmupi8rnkb',
size: 23,
price: 370
}
];
const columns = [
{
title: 'Price',
dataIndex: 'price',
key: 'id',
render: (price, record) => (
<Typography.Text style={{ fontSize: record.size }}>
{price}
</Typography.Text>
)
}
];
export default function App() {
return (
<FlexBox>
<Table
rowKey={record => record.id}
dataSource={dataSource}
columns={columns}
/>
</FlexBox>
);
}

Resources