I am working on setting an onClick
within a template string. The button is rendering as expected, but I am not getting my console log as I expect from the button click. I am basically running a server response through a parser and based off of what I getting back I am either rendering a button or an anchor tag. The button will launch a modal, while the anchor tag will just take the user to another link.
For simplicity purposes I am just setting my 2 outcomes to vars here
const testButton = `<button onClick="${()=> console.log('testing click')}">test</button>`;
const testAnchor = `<a href="${passedURL}" target="_blank">${someText}</a>`;
The anchor tag fully works as expected, but the button is not liking the onClick
. I am thinking it has something to do with that.
This is on the client side within a .ts
file.
2
Answers
The code within the
onclick
attribute of a button should not typically be a function definition, but rather code to execute. In your case, clicking the button does not call the function() => console.log('testing click')
, but rather defines the function with each click, which is meaningless.What you intend to say is probably
const testButton = `<button onClick="console.log('testing click')">test</button>;
.That said, adding onclick handlers this way is not good practice. Consider creating a new button element using the dom APIs and appending a click listener to that button instead of the above.
When dealing with template strings in JavaScript (or TypeScript) and adding event listeners such as
onClick
, the event listener won’t work directly when using the approach you mentioned. The issue arises because theonClick
attribute in the HTML string is not evaluated as a function when the string is converted to HTML.Instead, you should add the event listener programmatically after the element has been inserted into the DOM. Here’s how you can achieve that:
Here’s an example demonstrating this approach: