I have react APP that will do server render first to create html markup then do client render on browser again.
my app returns
<img classname="classA" src="invalid-src" fallbacksrc="valid-src" style="visibility:hidden"/>
I am trying to use onerror event handler to replace src with valid fallback src, and use onload handler to remove style="visibility:hidden". I know React has onError and onLoad, but since i use server side render, the static html will be generated, I would like to use html native onerror and onload event handler because i do not want to wait client side react rendering with javascript.
what I did is I manually add event handler in my html template
<html>
<{react-server-rendered-html}/>
<script>
var images = document.getElementsByClassName("classA");
for (img of images) {
img.addEventListener("error", function e() {
const i = this.getAttribute("fallbacksrc");
i && (this.src = i), this.removeEventListener("error", e)
}), img.addEventListener("load", function e() {
console.log("onloading", this.src), "hidden" === this.style.visibility && (this.style.visibility = null), img.removeEventListener("load", e)
});
}
</script>
</html>
This works fine except the load event executed after React render on client side. I did the workaround to add a < div > wrapper to my < img >, the problem is solved, load event executed before client side react render. However, I would like to see if there is any solution that does not need to add extra wrapper.
PS. wrapped with React.Fragment is not working as well.