Search code examples
javascriptreactjstypescript

Setting onClick within template string


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.


Solution

  • 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.