Reputation: 486
How can we create table row using JavaScript
I was trying to create table row from array of objects in javascript using map function but somehow its throwing error
const renderTableData = (result) => {
return result.map((item, index) => {
return (
<tr>
<td >item.Name</td>
<td >item.Date</td>
<td >item.state</td>
</tr>
)
})
}
const dataBinding = (result) => {
let x = document.getElementById("tableSection");
x.innerHTML = renderTableData(result);
}
my html <table> <tbody id = "tableSection"> </tbody></table>
Upvotes: 0
Views: 1942
Reputation: 173
You should use a template string
const renderTableData = (result) => {
return result.map((item, index) => {
return `<tr>
<td >${item.Name}</td>
<td >${item.Date}</td>
<td >${item.state}</td>
</tr>`;
}).join('');
};
const dataBinding = (result) => {
let x = document.getElementById("tableSection");
x.innerHTML = renderTableData(result);
};
dataBinding([
{ Name: "first", Date: "2020-09-21", state: "USA" },
{ Name: "first", Date: "2020-09-21", state: "USA" },
{ Name: "first", Date: "2020-09-21", state: "USA" },
]);
<table>
<tr>
<th>Name</th>
<th>Date</th>
<th>state</th>
</tr>
<tbody id="tableSection"></tbody>
</table>
I used template string as we need to create for each item a multiline string. We could have achieved the same result with normal string but would have been much less readable.
"<tr>\
<td >"+item.Name+"</td>\
<td >"+item.Date+"</td>\
<td >"+item.state+"</td>\
</tr>"
After we map over the array of objects we end up with an array of strings. .join('')
creates a single string out of that array and removes also the commas(if you set the innerHTML to an array, the commas between the elements will be considered as text to parse).
When you set the innerHTML of an element, the provided string is parsed as HTML. You can read more about it here
What you did on the first place was not valid javascript code, you were using a sort of JSX
Upvotes: 3