I received a base64 string as image from the server and I need to set src of html img tag. When I set the state of img in useEffect hook it doesn't show in browser.
In Chrome browser it gives me net::ERR_INVALID_URL error in the javascript console.
import React, { useState, useEffect } from "react";
function Captcha(props) {
const [captchaImg, setCaptchaImg] = useState("");
useEffect(() => {
setCaptchaImg("iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==");
}, []);
return (
<div>
<img
alt="captcha"
id="dnt-captcha-img"
src={`data:image/png;base64,${captchaImg}`}
/>
</div>
);
}
export default Captcha;
You have to specify the correct Content-type, Content-encoding and charset (eg. data:image/jpeg;charset=utf-8;base64):
/*depends on what you want to pass, might not be needed here*/
setCaptchaImg("data:image/jpeg;charset=utf-8;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==");
return <div>
<img
alt="captcha"
id="dnt-captcha-img"
src=data:image/jpeg;charset=utf-8;base64, {captchaImg}
/>
</div>