Sometimes, we want to fetch image from API with React.
In this article, we’ll look at how to fetch image from API with React.
How to fetch image from API with React?
To fetch image from API with React, we can use the fetch
function.
For instance, we write:
import React, { useEffect, useState } from "react";
const imageUrl = "https://i.imgur.com/fHyEMsl.jpg";
export default function App() {
const [img, setImg] = useState();
const fetchImage = async () => {
const res = await fetch(imageUrl);
const imageBlob = await res.blob();
const imageObjectURL = URL.createObjectURL(imageBlob);
setImg(imageObjectURL);
};
useEffect(() => {
fetchImage();
}, []);
return (
<>
<img src={img} alt="icons" />
</>
);
}
We call fetch
with the imageUrl
to make a GET request to it.
Then we call res.blob
to convert the response object to a blob.
Next, we call URL.createObjectURL
with the imageBlob
to convert it to a URL string that we can set as the src
attribute of the img element.
Finally, we call setImg
with imageObjectURL
so we can set img
as the value of src
to display it.
Conclusion
To fetch image from API with React, we can use the fetch
function.
8 replies on “How to fetch image from API with React?”
Hi,
I believe fetchImage will change the dom and will trigger useEffect.
!image && await fetchImage();
would prevent this loop.
Cheers
If you will give bad url then it will crash the site. The site will become unresponsive and errors in cosole.
You can put the code in a try block to prevent that.
How can we load an image which are on CDN? I tried like
It gets render on client side(browser) but didn’t get render by server(). I check doc preview (chrome devtool) it’s showing blank space.
Is the server CORS enabled?
Hi, can you tell me what theme are you using for code blocks? I see that you use shiki but I can’t find your theme anywhere. Thanks
There’s no theme for the code blocks. I used Jetpack.
just perfect sharing thanks