Sometimes, we want to display binary data as image in React.
In this article, we’ll look at how to display binary data as image in React.
Display Binary Data as Image in React
To display binary data as image in React, we can convert the image’s binary data to a base64 URL.
Then we can set the src
attribute of the img element to the base64 URL.
For instance, we write:
import React, { useEffect, useState } from "react";
const imageUrl =
"https://i.picsum.photos/id/566/200/300.jpg?hmac=gDpaVMLNupk7AufUDLFHttohsJ9-C17P7L-QKsVgUQU";
export default function App() {
const [imgUrl, setImgUrl] = useState();
const getImg = async () => {
const response = await fetch(imageUrl);
const imageBlob = await response.blob();
const reader = new FileReader();
reader.readAsDataURL(imageBlob);
reader.onloadend = () => {
const base64data = reader.result;
setImgUrl(base64data);
};
};
useEffect(() => {
getImg();
}, []);
return (
<div>
<img src={imgUrl} alt="" />
</div>
);
}
We have the getImg
function that makes a GET request to get an image from the imageUrl
with fetch
.
Then we call response.blob
to convert the binary data response to a blob object.
Next, we create a FileReader
instance and call the readAsDataURL
method on it with the imageBlob
blob object as the argument to convert the data into a base64 URL string.
Finally, we call setImgUrl
with the base64 string to set the imgUrl
value to the base64 string.
And then we use imgUrl
as the value of the img element’s src
attribute.
Now we should see the image displayed on the screen.
Conclusion
To display binary data as image in React, we can convert the image’s binary data to a base64 URL.
Then we can set the src
attribute of the img element to the base64 URL.