0

I have been trying to render image in an external web-component inside react but couldn't do it.

I am working on a react app that would use HTML template that can be run in browser, template is something like:

<script src="https://assets.some-domain.com/someBundledjs.js"></script>
<ParentForm>
  <ChildForm name="entryForm" image-src="https://www.image-domain.com/person1.jpg">
  </ChildForm>
</ParentFrom>

I tried to render it in reactDOM using react-helmet. Everything works fine except the image doesn't load in browser(though the call to fetch the image succeeds). When I debugged(luckily I have access to source code generating above form), I came to know that that the image is loading during server-side rendering, before js is downloaded, hence the image.onLoad() callback in the source code is never called. I verified it as per ref.

Update(rendering js without react-helmet):

I tried rendering below in react after loading script by doing something like:

componentDidMount () {
    const script = document.createElement("script");

    script.onload = () => {
      // script has loaded, you can now use it safely
      this.setState({ isLoadParentForm: true });
     
    }
    script.src = "https://assets.some-domain.com/someBundledjs.js";
    script.async = false;
    document.body.appendChild(script);
    
 
}

render(){
  return(
     <div> 
        {this.state.isLoadParentForm? 
         <ParentForm>
          <ChildForm name="entryForm" image-src="https://www.image-domain.com/person1.jpg">
          </ChildForm>
        </ParentFrom>
       : <></>
        
    </div>
   )
}

This ensures that the component is rendering post the script has loaded, still the image doesn't load inside the component.

Can someone explain and provide solution?

Retzah
  • 31
  • 4
  • Assign src before setting onload https://stackoverflow.com/questions/16230886/trying-to-fire-the-onload-event-on-script-tag – Loveen Dyall Nov 19 '20 at 20:39
  • Thanks for pointing to this. It still doesn't work. – Retzah Nov 20 '20 at 04:26
  • What is in your childform? In my experience I don't like to use onLoad in tag because onLoad doesn't call sometimes (e.g when it's load from cache). Can you share your childform component. – Someone Special Nov 20 '20 at 04:36
  • childForm component is provided by an external source and I don't have liberty to make any changes in it (though I have access to it source code). It has code for setting image which is something like: ```const image = new Image(); image.onerror = () => { // handle error } image.onload = () => { // handle load } image.src = imageSrc; ``` – Retzah Nov 20 '20 at 04:41

1 Answers1

0

After spending lot of time I finally figured out the root cause. The react-app that we are using downloads bunch of javascript libraries. One of those libraries has a js file that overrides the Image constructor. Due to this the image src was not getting set as expected and hence the image failed to load.

Retzah
  • 31
  • 4