0

I am fetching data (html content) from an API and setting it as an dangerioslyinnerhtml in ReactJS. I want to make an image popup using fancyapps/UI and in order to do that, I have to replace this,

<div className="img-parent">
    <img className='fancybox' src="" alt="" />
</div>

with this

<Fancybox options={{ infinite: false }}>
    <button
      data-fancybox="gallery"
      data-src={require("source-of-image")}
      className="button button--secondary">
      <img className='fancybox' src={require("source-of-image")} alt="" />
    </button>
</Fancybox>

Any ideas with .replaceAll function in JS?

I tried to explain my problem in details and I want some experienced people to help.

Rahul Rahatal
  • 648
  • 5
  • 19
  • What have you tried? Where did you encounter a problem? Why should a string be replaced(a block of html in your case) to make an image pop up? – Juljo Shahini Jan 12 '23 at 08:57
  • I tried using .replaceAll and its easy to replace the start of the image(replacing – goga goglika Jan 12 '23 at 09:03
  • Can you not add a ternary operator and display the first code or the second according to a state ? – Johan Jan 12 '23 at 09:09
  • Why are you fetching HTML in the first place? Can't you just get the image source? – Reyno Jan 12 '23 at 09:11
  • yes, I can control it using state. am fetching HTML because it comes from CMS which creates content pages using HTML, it is inside of text so I cant get img source particularly – goga goglika Jan 12 '23 at 09:11

1 Answers1

0

An approach would be to parse the response you are getting as html as explained here:

const parser = new DOMParser();
const htmlDoc = parser.parseFromString(txt, 'text/html');

and then you get the data you need to display your FancyBox components like this:

const images = [];
htmlDoc.querySelectorAll(".img-parent img").forEach(img=>{
   images.push({src:img.src, alt:img.alt})
});