I have an onClick event that comes from a String as follows.
const text = `some text and <sup onClick={handleClick}>123</sup>`;
This text is actually coming from an external API response.
And I have a handleClick function as follows:
const handleClick = () => alert('clicked!');
This handleClick function is in my component. I expect the alert to occur when the sup text 123 is clicked.
The text is clickable, but when I click it, I get the error:
Unhandled Runtime Error
ReferenceError: handleClick is not defined
Call Stack
HTMLElement.onclick
But handleClick is there in the component.
I even validated it with a button that doesn't use the text. That works fine.
Why doesn't it work for the text and how could I resolve this?
Component
export default function Home() {
const handleClick = () => alert('clicked!');
const text = `some text and <sup onClick={handleClick}>123</sup>`; // assume this comes from an api.
return (
<div>
<div dangerouslySetInnerHTML={{ __html: text }} /> // this is the line throwing error when I click it.
// this button shows the alert fine when clicked.
<button
onClick={handleClick}
>
Click me now!
</button>
</div>
)
}
useEffectthat adds the function to the global scope? And is it possible to not have the inner html be jsx?dangerouslySetInnerHTMLexpectsHTMLand not JSX in which caseonClick={handleClick}doesn't mean anything. It would need to beonclick="handleClick()"as you would pass to a regular HTML element.createElement(but asyncawaits comment re: scoping will still need to be looked into)