JSFiddle - React, Tailwind, and code Playground
by Vadim Shaikhislamov
HTML
<table id="tbl">
<thead>
<tr>
<th>id</th>
<th>info</th>
<th>user</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button type="button">Refresh DATA</button>
CSS
table {
border-collapse: collapse;
margin-bottom: 20px;
}
table th, table td {
border: 1px solid black;
padding: 10px;
}
JavaScript
function refreshData(selector, data) {
let table = document.querySelector(selector);
if (table) {
let tbody = '';
for (let obj of data) {
let row = `<tr><td>${obj.id}</td><td>${obj.info}</td><td>${obj.user}</td></tr>`;
tbody += row;
}
table.querySelector('tbody').innerHTML = tbody;
} else {
throw new Error("Selector not exists!");
}
}
const shortFunc = (selector, data) => {
let table = document.querySelector(selector);
if (!table) throw new Error("Selector not exists!");
table.querySelector('tbody').innerHTML = data.map(item => `<tr><td>${item.id}</td><td>${item.info}</td><td>${item.user}</td></tr>`).join("");
}
const randomize = (data, min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
data = data.map(item => {
item.id = Math.floor(Math.random() * (max - min)) + min;
return item;
})
}
json = [
{"id": "1", "info": "first", "user": "racoon"},
{"id": "2", "info": "second", "user": "bear"},
{"id": "3", "info": "third", "user": "rabbit"}
];
document.querySelector("button").onclick = function() {
randomize(json, 1, 100);
shortFunc("#tbl", json); // refreshData("#tbl", json)
}