0

I am using React.js as Frontend framework,

I have an icon from antd, and I want to put it in the 'alt' prop of an image tag, so in case that the url I pass there will be null - it will go to put the icon there.

I tried using 'alt' but it only accepts string. is it possible to put there an icon? (like one from antd?)

to emphasize - I want to add it as - <Image alt={<StepBackwardOutlined />}

as in in an actual icon and NOT AS A URL.

Tzachi Elrom
  • 385
  • 1
  • 2
  • 19

2 Answers2

1

Use the onerror attribute.

From the docs:

<img src="imagefound.gif" onerror="this.onerror=null;this.src='logoIcon.jpg';" />

Here logoIcon.jpg is the icon path.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
1

You can use on onError. Inside onError you can create a function outside the main return for ex:-

const onErrorImage = ((e) => {
  e.target.src = <StepBackwardOutlined />
})

<img onError={onErrorImage} />

I never tried it with a component....and i never saw someone using it....so i am not sure that it will work or not.

  • thanks but it doesn't work - throws the browser into an endless loop for api requests, I guess because 'src' expects a link and not an Icon – Tzachi Elrom Dec 19 '21 at 16:33
  • 1
    @TzachiElrom Well i tried another way of doing it......it is not a good way to handle this......but it is working.......Here is the link for it :- [link](https://codesandbox.io/s/eager-neumann-zrcy0?file=/src/App.js) ......If you find it working you can use it in your project....I am mentioning again that it's not the best way to do it. – ujjwal sharma Dec 20 '21 at 09:23
  • that's a funny workaround! thanks! (though I do hope I won't have to use it) – Tzachi Elrom Dec 20 '21 at 13:40