Reputation: 3984
I want to create entire table from a JSON array include dynamic th
s, so a decoupled the head part to:
import React from 'react';
import TableDataTR from './TableTRView';
const TableView = ({ thds, tableData }) => {
if (!thds) {
return <table></table>;
}
return (
<div>
<table>
<thead>
<tr>
{thds.map((data, i) => <th key={i}>{data.th}</th>)}
</tr>
</thead>
<TableDataTR tableData={tableData}/>
</table>
</div>
)
}
export default TableView;
And the table prints the head part, but I am having trouble printing my tbody
:
import React, { Component } from 'react';
class TableDataTR extends Component {
render() {
let rows = this.props.tableData.map((currElement, index) =>{
return(
<tr key={index}>
<td>currElement[index]</td>
</tr>
)
});
return (
<tbody>{rows}</tbody>
);
}
}
export default TableDataTR;
Example data, table head
thds : [ { th: 'th1' },
{ th: 'th2' }]
tableData:[ { tdData1: 'somedata', tdData2: 'somedata2' },
{ tdData1: 'somedata', tdData2: 'somedata2' },]
The table head works fine, but the data inside tbody
is not displaying at all.
The final goal is to get any 2 arrays and display the table accordingly.
Upvotes: 0
Views: 1518
Reputation: 1097
You need to access the table data using key name as
let rows = this.props.tableData.map((currElement, index) => {
return (
<tr>
{ Object.keys(currElement).map((item) =>
(
<td>{currElement[item]}</td>
)
)}
</tr>
)
});
Upvotes: 1
Reputation: 17608
There is a typo again in your <td>..</td>
part, missing {}
for your expression. For the dynamic solution after first map you need to map your Objects as well.
<tr key={index}>
<td>
{
Object.keys(currElement).map(key => currElement[key])
}
</td>
</tr>
Upvotes: 0