I am having below code.
if (response.ok) {
response.json().then((data: any) => {
//use data
console.log(data.value);
let strFilesDisplayTable = "";
strFilesDisplayTable =
"<table border='1'> <tr> <th> Name </th> <th > Uploaded Date </th> <th > Role </th> <th > Remove </th></tr>";
for (var c = 0; c < data.value.length; c++) {
var dateVal = new Date(data.value[c].TimeCreated);
var docIdVal = data.value[c].ListItemAllFields["Role"];
let dateTimeCreatedMod =
dateVal.getDate().toString() +
"/" +
(dateVal.getMonth() + 1).toString() +
"/" +
dateVal.getFullYear().toString();
strFilesDisplayTable =
strFilesDisplayTable +
"<tr> <td > " +
data.value[c].Title +
" </td> <td>" +
data.value[c].Title +
" </td> <td style='padding:5px;'> " +
dateTimeCreatedMod +
" </td> <td style='padding:5px;'> " +
data.value[c].ListItemAllFields["Role"] +
" </td> <td> <button class='btnDelDoc' onClick={this.tempFunDel(" +
data.value[c].ListItemAllFields["ID"] +
")}> Delete </button> </td> </tr> ";
}
strFilesDisplayTable = strFilesDisplayTable + "</table>";
document.getElementById("showFilesDiv").innerHTML = strFilesDisplayTable;
});
}
and my function is
public tempFunDel(idVa){ alert("Id is !" +idVa); }
It renders one table for me. When I click on delete button nothing happens function "tempFunDel"
is not getting called. Please suggest a workaround to call the function in the HTML string.
Thanks in advance.
2
Answers
It is an anti-pattern in React to assemble HTML using strings and updating the DOM with the
innerHTML
property. Instead components accept properties and construct HTML elements directly using inline JSX . Run the demo below to see a minimal, reproducible example in your own browser.If the data for the Table is arriving asynchronously, a parent component can handle the request, the supplying the data to the table as props after it has loaded successfully.
Of course you can imagine a big headache if you have to write this for every component that needs to make a JSON request. Writing good programs means extracting behaviors so they can be easily reused –
Now writing
App
is a breeze –You’re calling the following in your structure:
To call a function with parameters, according to the official documentation, you have to do the following:
Link to the ReactJS documentation: https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers