JSFiddle - React, Tailwind, and code Playground
HTML
<button onclick="populate()">Test</button>
<table class="test-table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
CSS
table { border-collapse: collapse; border: solid 1px #000; overflow: hidden; }
table table { margin: 10px; }
th, td { border: solid 1px #000; text-align: left; padding: 5px; }
/*table table { display: none; margin: 10px; }
input[type=checkbox] { display: none; }
input[type=checkbox]:checked + table { display: table; width: calc(100% - 20px); }
label { cursor: pointer; position: absolute; top: 0; left: 0; bottom: 0; width: 1000px; z-index: 2; }
table > tbody > tr:nth-child(2n) > td { padding: 0; }
table > tbody > tr:nth-child(2n) > td td { padding: 5px; }
th, td { border: solid 1px #000; text-align: left; padding: 5px; position: relative; }
*/
tr.mainTableRow:hover {
cursor: pointer;
background-color: rgba(255, 255, 0, 0.2);
}
JavaScript
function populate(){
var data = [
{
"ID" : "2",
"FirstName" : "John",
"LastName" : "Test",
"DOB": "03-12-1959",
"Gender":"M"
},
{
"ID" : "3",
"FirstName" : "Helen",
"LastName" : "Test",
"DOB": "03-12-1959",
"Gender":"M"
},
{
"ID" : "4",
"FirstName" : "John",
"LastName" : "Test",
"DOB": "03-12-1959",
"Gender":"M"
}
];
// Dummy data for nested tables.
var nestedTablesData = [
{
"ID" : "2",
"PhoneNumber": "555-3226 (id2)",
"City": "New York (id2)",
"HireDate": "8/13/12 (id2)",
"Salary": "$48,000 (id2)"
},
{
"ID" : "3",
"PhoneNumber": "555-3226 (id3)",
"City": "New York (id3)",
"HireDate": "8/13/12 (id3)",
"Salary": "$48,000 (id3)"
},
{
"ID" : "4",
"PhoneNumber": "555-3226 (id4)",
"City": "New York (id4)",
"HireDate": "8/13/12 (id4)",
"Salary": "$48,000 (id4)"
}
];
// Fill main table
var rowsHtml = "",
rowData;
// loop through data source
for (var i = 0; i < data.length; i++) {
// Cache the current row data.
rowData = data[i];
// Use either string concatenation then innerHTML, or batch nodes insertion for better performance
// see https://jsperf.com/innerhtml-vs-createelement-test
rowsHtml +=
// Store the index in TR dataset to link with data for nested table.
"<tr class='mainTableRow' data-nestedtableindex='" + i + "'><td>" + rowData.ID
+ "</td><td>" + rowData.FirstName
+ "</td><td>" + rowData.LastName
+ "</td><td>" + rowData.DOB
+ "</td><td>" + rowData.Gender
+ "</td></tr>";
}
// Finally append to your already existing table.
var tbody = document.getElementById("data");
tbody.innerHTML+= rowsHtml;
...