0

My code

import React, { Component } from 'react';
import './App.css';


class App extends Component {
  state = {
    loaded: false,
    error: false
  }

  onImageLoad = () => {
    this.setState({
      loaded: true
    })
  }

  onImageError = () => {
    this.setState({
      error: true
    });

  }

  render() {
    // let imgSrc = (!error) ? src: fallbackSrc
    return (
     <div>
        <img src= {'https://unsplash.com/photos/wQLAGv4_OYs'} alt={'Wresting Character'} onLoad={() => this.onImageLoad()} onError={require('../src/images/batista.jpg')} />
      </div>
    )
  }
}



export default App;

I want to show the fallback image if the url is broken. Right now the default image shows but if I change the url of it the page throws an error. How do I get to show the dummy image incase if my link is broken.

Vishal Sharma
  • 63
  • 1
  • 6

2 Answers2

1

You can fallback to default image once the error occurs:

onImageError = (ev) => {
  this.setState({
    error: true
  });
  ev.target.src = 'some default image url';
}
dima golovin
  • 262
  • 2
  • 8
1

I would rather use the onerror attribute on the img tag. You can define a handler for the error, and replace the target source attribute with your fallback URL.

Jason
  • 11,263
  • 21
  • 87
  • 181
  • Could you please elaborate as I am using it on the image tag itself as of now. – Vishal Sharma Dec 22 '19 at 13:44
  • you would return the URL you want to use, not the file path. You've defined the file path to the image as part of the `Batista` and `Game` imports, but those are not accessible via a URL. eg, you need something like `/image/assets/someimage.jpg` – Jason Dec 22 '19 at 13:51
  • I tried but this does not seem to work. Sharing a screenshot of the same https://imgur.com/a/8trJG9c – Vishal Sharma Dec 22 '19 at 14:03
  • don't use `require`. use the actual URL path. eg `src="/image/assets/triple_h.jpg"` – Jason Dec 22 '19 at 14:05
  • It does not work without require. Here is where I found require from https://stackoverflow.com/questions/34582405/react-wont-load-local-images – Vishal Sharma Dec 22 '19 at 14:06
  • 1
    ok, so its a local image, not one that's available elsewhere. Check the second answer for that question. – Jason Dec 22 '19 at 14:08
  • 1
    You cannot test your app with an error image that is loaded using import. You need to pass a valid URL that returns no image. What you are doing now is similar to importing a non-existing class/package/file. It will throw a build error. You can ONLY import/require existing files. – dima golovin Dec 22 '19 at 14:09
  • @dimagolovin alright so I have removed the import. I have updated my question. Please have a look and guide me. Thanks – Vishal Sharma Dec 22 '19 at 14:12