25

I'm writing a module that takes article data from json and shows a large image over the article text, a hero module as they say.

I've got the data and have set it up so if there is an image, it will show that image and if there is no image in the data, it will show a default image. Problem is that this method doesn't replace broken links to show the default image.

I'm still new to react and using state ... question is, should I be using state to check for the broken link and how do I do it?

This is how I get the data in as props in the module:

const { newsItemData: {
          headline = '',
          bylines = [],
          publishedDate: publishDate = '',
          updatedDate: updatedDate = '',
          link: newsLink = '',
          contentClassification: category = '',
          abstract: previewText = '',
          abstractimage: { filename: newsImage = '' } = {},
          surfaceable: { feature: { type: featureType = '' } = {} } = {},
        } = {},
        wideView,
        showPill,
        defaultImage } = this.props;

I display the info in this way:

<div className={imageContainerClassName} style={customBackgroundStyles}>
      {newsImage ? <img className="img-responsive" src={newsImage} alt={headline}/> : <img className="img-responsive" src={defaultImage} alt={headline}/>}
</div>

What should I do in order to also check for broken images? I think this is all the pertinent data needed, let me know if I should show anything else. Thanks!

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
nyhunter77
  • 614
  • 2
  • 7
  • 19
  • I wrote something that can address this: https://github.com/mbrevda/react-img-multi – Mbrevda Apr 04 '17 at 18:47
  • Found this video tutorial on this - https://youtu.be/90P1_xCaim4 which actually helped me building a full fledged image component for my application. I also found this along with which is awesome preloaders for my image component - https://youtu.be/GBHBjv6xfY4. By combining both you can provide a wonderfull UX for the users. – Prem Jan 13 '19 at 16:11

8 Answers8

87

There is a native event for images called onerror that lets perform an action if the image cannot be loaded.

<img onError={this.addDefaultSrc} className="img-responsive" src={newsImage} alt={headline}/>

//in your component
addDefaultSrc(ev){
  ev.target.src = 'some default image url'
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
eltonkamami
  • 5,134
  • 1
  • 22
  • 30
  • 1
    @nyhunter77 the fired when column can help you out. but you will have to track down your issue. in this case that column says `A resource failed to load.` – eltonkamami Jul 22 '16 at 14:35
  • 1
    `onError` is marked as deprecated now (and it doesn't seem to work anymore). Do you know what's the best approach for the new versions? – Adrian Pop May 02 '19 at 22:58
  • @AdrianPop this is still working. Tested in Chrome 88 – Nuhman Feb 22 '21 at 13:29
  • If you like me using React look at this answer https://stackoverflow.com/a/48222599/13162807 – Alexander P Mar 10 '22 at 11:50
3

In case that you know the image's error will be the absence of it like you are looping a gallery of profiles and some of them do not have pictures available, then you can simply insert the image's path as a callback like this:

<img
   height="auto"
   width={140}
   src={bizLogo || "/img/error.png"}
   alt="test"
/>
Luis Febro
  • 1,733
  • 1
  • 16
  • 21
2

Here is what I did to check if the image is broken. There is an attribute called onError which is called when the image is broken or cannot be loaded. For example, here is the img tag:

<img id={logo.id} src={logo.url} alt ={logo.name} onError={this.handleImageError} />

How I handled the error:

handleImageError = e => { //write your logic here.}
dhellryder
  • 89
  • 1
  • 8
1

As mentioned, onError is the way to go.

If you're looking for a component that handles this for you, try https://github.com/socialtables/react-image-fallback

Petr Bela
  • 8,493
  • 2
  • 33
  • 37
0

According to my understanding you want to see broken images. you should call a method in onError attribute. Check this jQuery/JavaScript to replace broken images

Community
  • 1
  • 1
waqas ali
  • 603
  • 6
  • 13
  • As I understand it, it's bad form to mix Jquery and React JS. So far i haven't needed to but I do feel at times like I have one arm tied behind my back – nyhunter77 Jul 22 '16 at 13:41
  • yes of course. i am just giving you hint how to do this. react also use onError attribute and if you are working on react you know how to call a component method on attribute like onError={somecomponentmethod} in image tag. – waqas ali Jul 22 '16 at 13:46
  • Yep, thanks, I tried a few methods similar to the "Jquery way" or pure JS way but I wasn't successful – nyhunter77 Jul 22 '16 at 13:49
0

In my case was intend to use in a component using map() function, in that scenario was need to change e.target.src to e.currentTarget.src, like code bellow:

    <img src={original.image} 
         alt=""
         onError={e => { e.currentTarget.src = "your_image_not_found_defalt_picture_here"; }}
    />
0
import { useState } from "react";
import "./styles.css";
export default function App() {
  const url = "https://secure.gravatar.com/avatar?d=wavatar";
  const [showImage, setShowImage] = useState(true);
  const hideImg = (event) => {
    // this.setState({ showImg: false });
    setShowImage(false);
  };
  return (
    <div>
      {showImage ? (
        <img src={url} alt="perkimage" onError={hideImg} />
      ) : (
        "Default text or image"
      )}
    </div>
  );
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 09 '22 at 22:00
0

You don't have to rewrite the entire img element. Instead, you can write it like this:

  <img className="img-responsive" src={newsImage ? newsImage : defaultImage} alt={headline}/>
JShoe
  • 3,186
  • 9
  • 38
  • 61