I'm dynamically generating some HTML and I want some "events" to have an onclick component that calls a simple function. I'm working with react and typescript.
This is what I'd imagine would work:
function add_event(day: number, month: number, events: any) {
let event_html = "";
events[month].forEach((event: any) => {
const event_date = new Date(event.activity_start_date);
if (event_date.getMonth() == month && event_date.getDate() == day) {
event_html = `<table><td onclick='select_event()' class='event'>${event.activity_name}</td></table>`;
}
});
return event_html;
}
function select_event(){
console.log('selected')
}
However, I get this error "Uncaught ReferenceError: select_event is not defined at HTMLTableCellElement.onclick"
I'm guessing the problem is that the function only lives in this local tsx file and not the HTML file built by react. How can I go about solving this?
CodePudding user response:
May be you can inline your select_event
function to the generated html string.
CodePudding user response:
I think you should return JSX instead of string as you are using react. This should be more practical. The code below should help you grasp the concept.
function add_event(day: number, month: number, events: any) {
let event_html = events[month].map((event: any, index: number) => {
const event_date = new Date(event.activity_start_date);
if (event_date.getMonth() == month && event_date.getDate() == day) {
return (<table key={index}><td onclick='select_event()' class='event'>${event.activity_name}</td></table>);
}
});
return event_html;
}
function select_event(){
console.log('selected')
}
return(<div>{add_event(day, month, events)}</div>)
Just in case you are getting string html response from a server, in that case try to set id for the table and listen for click events that way.