Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change with fallback image with Material ui?

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.

like image 443
gwrik09 Avatar asked Sep 18 '25 05:09

gwrik09


2 Answers

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,
    }}
    />
  )
};

Edit how-to-change-with-fallback-image-with-material-ui

like image 142
Drew Reese Avatar answered Sep 19 '25 21:09

Drew Reese


I would change the logic for the fallback image like this:

 <Avatar
   src={product?.image || fallbackImage}
   alt={product?.title}
   variant='rounded'
 />
like image 21
Java Avatar answered Sep 19 '25 19:09

Java