Reputation: 121
I'm trying to fill table from data in React, however I am getting an above mentioned error.
this is the function which fills the table:
let numberOfColumns = props.tabColumns.split(",").length;
let tableData = props.tabRows.split(",");
function generateRows(){
let r = ``;
for (let i=0; i<tableData.length/numberOfColumns; i++){
r =`${r}<tr>`;
for(let j=0; j<numberOfColumns; j++){
r = `${r}<td>${tableData[i*numberOfColumns+j]}</td>`;
}
r =`${r}</tr>`;
}
console.log(r);
return r;
}
This is the table:
<table>
<tbody>
<tr>
{props.tabColumns.split(",").map((column, index) => <th key={"column"+index}>{column}</th>)}
</tr>
{generateRows()}
</tbody>
</table>
Data:
tabColumns: "Name,Age,Occupation",
tabRows: "John,18,Student," +
"Miranda,23,Nurse," +
"Ashley,32,Telephonist," +
"Rose,28,Driver"
Result looks like this: Problem is somewhere in the generateRows function. What could be the culprit? Thanks in advance.
Upvotes: 1
Views: 580
Reputation: 39182
Don't mix React rendering with manual html construction unless you really really need to. It eliminates the benefits of using React in the first place. Render your rows using React!
function renderRow(tableData, numberOfColumns, i) {
const cells = [];
for (const j = 0; j < numberOfColumns; ++j) {
cells.push(<td>tableData[i*numberOfColumns+j]</td>);
}
return <tr>{cells}</tr>;
}
render() {
const rows = [];
for (let i = 0; i < tableData.length / numberOfColumns; ++i) {
rows.push(renderRow(tableData, numberOfColumns, i);
}
return (
<table>
<tbody>
<tr>
{props.tabColumns.split(",").map((column, index) => <th key={"column"+index}>{column}</th>)}
</tr>
{rows}
</tbody>
</table>
);
}
Upvotes: 5
Reputation: 121
As people mentioned, generateRows is returning a string. To get what I needed I had to pass this string to a parser (https://www.npmjs.com/package/html-react-parser) which gave me the correct output.
Upvotes: 0