Saturday, 22 October 2022

Image onClick event attribute React

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

//Code

const parser = new DOMParser();
  
    const doc = parser.parseFromString(htmlContent,
      "text/html"
    );
 
    const imageData = doc.querySelectorAll("img");

 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) + '}

x.addEventListener('onClick', () => setOpen(true));

htmlContent:

<p>new test <img src="https://i.imgur.com/7KpCS0Y.jpg%22" width="100" height="100" id="img_1665468977463_0"></p><p>new new test <img src="https://i.imgur.com/7KpCS0Y.jpg%22" width="100" height="100" id="img_1665468986873_0"></p><p>next level test <img src="https://i.imgur.com/7KpCS0Y.jpg%22" width="100" height="100" id="img_1665468996237_0"></p><p></p><p>format test</p><ol><li><p>one</p></li><li><p>two </p></li><li><p>three</p></li></ol>

Can i get any help?



from Image onClick event attribute React

No comments:

Post a Comment