Hi I am trying to change a fallback image of Material UI Avatar with my original fallback image. Does anyone know how to do this?
const fallbackImage = "../../fallback/img.png"
const AvatarWithBadge = (image) => {
const url = image ? image : fallbackImage;
return (
<Badge
overlap="circle"
anchorOrigin={{
vertical: 'bottom',
horizontal: 'right',
}}
badgeContent={
<NavigationIcon />
}
>
<Avatar
src={url}
className={classes.avatar}
imgProps={{
onError:(e) => { e.target.src = ${fallbackImg}`}
}}
/>
</Badge>
}
What I'm trying to do here is to listen to an error and replace with image from my own file. I would like to know how to listen when the image link is broken.
Avatar Fallbacks
If there is an error loading the avatar image, the component falls back to an alternative in the following order:
- the provided children
- the first letter of the alt text
- a generic avatar icon
This means you can simply provide the fallback image as a child of the Avatar
component
<Avatar
src={url}
className={classes.avatar}
>
<img className={/* css to style appropriately */} src={fallbackImg} />
</Avatar>
I was, however, able to get an implementation working (most of the time) that replaces the source url. It should be noted that I wasn't able to get this implementation to consistently work within codesandox (running in an iframe, react gets a little flaky sometimes)
const fallbackImage = "../../fallback/img.png"
const MyAvatar = ({ image }) => {
const [url, setUrl] = useState(image);
const errorHandler = () => {
setUrl(fallbackImage);
}
return (
<Avatar
src={url}
imgProps={{
onError: errorHandler,
}}
/>
)
};
I would change the logic for the fallback image like this:
<Avatar
src={product?.image || fallbackImage}
alt={product?.title}
variant='rounded'
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With