0

I'm trying to create a replacement for the image if not found and below is what I have so far. This is for a React project, so React answers only.

Any help will be great.

<img src={`${news.urlToImage.src ? news.urlToImage.src : "../assets/default_logo.png" }`} 
alt="images"/>

2 Answers2

0

You can have this approach here with uncontrolled component:

<img src={this.state.img} ref={img => this.img = img} onError={
    () => this.img.src = 'img/default.img'
}>

Also, you can find the same question here - react.js Replace img src onerror

thelovekesh
  • 1,364
  • 1
  • 8
  • 22
  • If you find another question which has answers which answer this question, please flag this question as a duplicate of that other question, and don't answer it. – Heretic Monkey Jun 16 '21 at 13:39
0

Here's a hooks-style version of Lovekesh's answer:

[imgSrc, setImgSrc] = useState(
  news.urlToImage.src ? news.urlToImage.src : 
  "../assets/default_logo.png");
//...
<img src={imgSrc} onError={
  () => setImgSrc("../assets/default_logo.png"")
}/>
edemaine
  • 2,699
  • 11
  • 20