[Web][JavaScript] Creating dynamic buttons with data in JavaScript
Creating dynamic buttons with data in JavaScript
While working on GTPS blog, I encountered a need of dynamically generating buttons that stores data from the API and triggers certain actions when clicked.
Solution: Leveraging Closure to have different data per button.
The point is that each row in the table should have the same structure but different data. Closure will help. In the example below, forEach() creates a new scope per iteration. Within it, the arrow function with onClick forms a closure, capturing the specific game in that iteration. So, a specific game is stored in each row.
function renderTable(games) {
const table = document.getElementById("game-table");
table.innerHTML = "";
games.forEach(game => {
const row = document.createElement("tr");
// Set the structure without the button
row.innerHTML = `
<td></td> <!-- Button goes here -->
<td>${game.title}</td>
<td>${game.platforms}</td>
<td>${game.release_date}</td>
<td>${game.genres}</td>
<td>${game.developers}</td>
<td><a href="https://wikidata.org/wiki/${game.wikidata_code}">LINK</a></td>
`;
// Create and attach the button
const button = document.createElement("button");
button.textContent = "ADD";
button.onclick = async () => {
await setUserGameData(game);
};
row.children[0].appendChild(button);
table.appendChild(row);
});
}
Why not use innerHTML to inject button right away
It could be easy to think insert the button right away into the row.
row.innerHTML = `<td>${button}</td>`;
However, this fails because the button is a DOM element and ${button} will be converted into the string [object HTMLButtonElement]. This is why the table or the HTML separately and the DOM element or the button should be inserted using appendChild()
Comments
Post a Comment