Home > other >  Image onClick event attribute React
Image onClick event attribute React

Time:10-19

I wanted to add onClick attribute to the image dynamically. But the click event didn't work.

//Code

 imageData.forEach((x: any) => {
     
            htmlContent = htmlContent.replace(
                x.outerHTML,
                '<img width="240" height="160" style="cursor: grab; margin: 10px;" src="'  
                  x.getAttribute("src")   '"onClick={() => setOpen(true)}/>'
              );
          });

Tried,

onClick={handleClick(true)}

const handleClick = (flag: boolean) => {
      setOpen(flag)
  }  

onClick={setOpen(true)}

onClick={() => '  setOpen(true)   '}

htmlContent is a string variable with HTML content. Can i get any help?

CodePudding user response:

Try adding it dynamically

htmlContent.addEventListener("click", handleOnClick, false);

const handleOnClick = () => {
   setOpen(true)
}

CodePudding user response:

Create a wrapper div outside the htmlcontent in the HTML markup which should not be replaced and attach event listener to that div

<div id="wrapper" onClick={handleOpen(true)}>
  //your HTML content
  {htmlContent}
 </div>

  • Related