React hooks: unable to get handler functions to work for custom-generated buttons
React hooks: unable to get handler functions to work for custom-generated buttons
Sorry if this is too React-specific but maybe someone has seen this behavior before.
I am trying to shift my (datatables-heavy) website to React - I got everything to work so far, except the following.
I am adding custom buttons to last column of every datatables row (in below case, column 10) with the following columnDefs:
{
"targets": [10],
createdCell: (td, cellData, rowData, row, col) => {
ReactDOM.render(
<button onClick={props.handleReportClick}></button>
, td);
}
})
The handler function (passed as props) is defined as follows:
const handleReportClick = (e) =>{
e.stopPropagation();
console.log(dataTable);
};
[The dataTable is a state variable where I store my dataTable and every other function that I have logs out dataTable as a full object]
The button shows up fine and triggers the handler function but I get 'empty string' logged out, which means it is probably just logging out the initial state of the dataTable but not the current state. I tried using useRef which did not help.
(If I replace the onClick function to just string name of the handler function (like I used to in my framework-less site then it doesn't work at all)
Any help would be appreciated.
Replies
I have resolved it using machnicki's answer here:
https://stackoverflow.com/questions/55265255/react-usestate-hook-event-handler-using-initial-state
Actually, the above solution was still giving me (other) problems. I found that, instead of passing function reference to the button renderer as in my original post, I set a unique data-id on each button (prefix + row in my case) and then add a 'click' event listener for all clicks on page. When a button gets clicked, event listener triggers a function that extracts the button's data-id from which I extract the row number. I can then access the dataTable object data for that row. That way everything works fine.
@auris2018 I've just registered to tell you that your question and solution had saved my life!!!
PS. Huge fan of DataTables