Sometimes, we want to replace img src onerror with React.
In this article, we’ll look at how to replace img src onerror with React.
How to replace img src onerror with React?
To replace img src onerror with React, we set the fallback image URL when there’s an error loading the image.
For instance, we write
import React, { ImgHTMLAttributes, useState } from "react";
export default function ImageWithFallback({ fallback, src, ...props }) {
const [imgSrc, setImgSrc] = useState(src);
const onError = () => setImgSrc(fallback);
return <img src={imgSrc ? imgSrc : fallback} onError={onError} {...props} />;
}
to create the imgSrc
state.
We set imgSrc
to src
initially.
Then we add the img element with an onError
prop that’s set to the onError
function.
In onError
, we call setImgSrc
to set the image URL to fallback
.
And then set the src
prop of the img element to imgSrc
or fallback
if imgSrc
isn’t set.
Conclusion
To replace img src onerror with React, we set the fallback image URL when there’s an error loading the image.