I have a react component that is the detail view from a list.
I am trying to replace the image with a default image if the image does not exist and there is a 404 er
For those like me who also wanted to change the styles of the element and/or change the img source, just do something like this:
<img
src={'original src url goes here'}
alt="example"
onError={(e) => {
e.target.src = '/example/noimage.png' // some replacement image
e.target.style = 'padding: 8px; margin: 16px' // inline styles in html format
}}
/>
Hope it helps!
I used the above method of Arthurs making e.target.onerror = null to stop the infinite loop , but still the infinite loop happened. So , to stop the infinite loop I had to use the below method.I had to find the actual property onError and make it null.
<img src={imageSource}
onError={(e) => {
e.target[Object.keys(e.target).filter(prop=>prop.includes('EventHandler'))[0]].onError = null;
e.target.src = 'images/avatar.png'; }}
/>
event.target properties
I wrote like this.
import React, { useState } from 'react';
import NoImageSVG from './noImage.svg';
const ImgWithFallback: React.FunctionComponent<{ src: string; alt: string; className: string }> = ({
src,
alt,
className,
}) => {
const [isUndefined, updateIsUndefined] = useState(false);
const onError = () => {
updateIsUndefined(true);
};
if (isUndefined) {
return (
<div className={className}>
<NoImageSVG width='5rem' height='5rem' />
</div>
);
}
return <img src={src} alt={alt} className={className} onError={onError} />;
};
export default React.memo(ImgWithFallback, () => true);
I took @Skay's answer and created a reusable Image component. Posting in case it helps anyone:
import React, { PropTypes } from 'react';
const Image = ({src, fallbackSrc, ...other}) => {
let element;
const changeSrc = newSrc => {
element.src = newSrc;
};
return (
<img src={src}
onError={() => changeSrc(fallbackSrc)}
ref={el => element=el}
{...other} />
);
};
Image.propTypes = {
src: PropTypes.string,
fallbackSrc: PropTypes.string
};
export default Image;