react.js Replace img src onerror

react check if image exists
react onerror event
img onerror
react-image
react image placeholder
react native image fallback
react dynamic image src
react replace img src

I have a react component that is the detail view from a list.

I am trying to replace the image with a default image if the image does not exist and there is a 404 error.

I would normally use the onerror method in the img tag but that doesn't seem to be working.

I am not sure how to do this with react.

Here is my component:

import React from 'react';
import {Link} from 'react-router';
import ContactStore from '../stores/ContactStore'
import ContactActions from '../actions/ContactActions';

class Contact extends React.Component {
  constructor(props) {
    super(props);
    this.state = ContactStore.getState();
    this.onChange = this.onChange.bind(this); 
 }

componentDidMount() {
  ContactStore.listen(this.onChange);
  ContactActions.getContact(this.props.params.id);
}

componentWillUnmount() {
  ContactStore.unlisten(this.onChange);
}

componentDidUpdate(prevProps) {
  if (prevProps.params.id !== this.props.params.id) {
    ContactActions.getContact(this.props.params.id);
  }
}

onChange(state) {
  this.setState(state);
}

render() {
  return (
    <div className='container'>
      <div className='list-group'>
        <div className='list-group-item animated fadeIn'>
          <h4>{this.state.contact.displayname}</h4>
          <img src={this.state.imageUrl} />
        </div>
      </div>
    </div>
  );
}
}

export default Contact;

Since there is no perfect answer, I am posting the snippet I use. I am using reusable Image component that fallbacks to fallbackSrc.

Since the fallback image could fail again and trigger infinite loop of re-rendering, I added errored state.

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Image extends Component {
  constructor(props) {
    super(props);

    this.state = {
      src: props.src,
      errored: false,
    };
  }

  onError = () => {
    if (!this.state.errored) {
      this.setState({
        src: this.props.fallbackSrc,
        errored: true,
      });
    }
  }

  render() {
    const { src } = this.state;
    const {
      src: _1,
      fallbackSrc: _2,
      ...props
    } = this.props;

    return (
      <img
        src={src}
        onError={this.onError}
        {...props}
      />
    );
  }
}

Image.propTypes = {
  src: PropTypes.string,
  fallbackSrc: PropTypes.string,
};

React Fallback for Broken Images Strategy - Dani Shulman, <img src="image.png" onError="this.onerror=null; In React we can also use onError, and trigger a function that can deal with it the broken discuss.reactjs.​org. Stack Overflow Public questions and answers; Teams Private questions and answers for your team; Enterprise Private self-hosted questions and answers for your enterprise; Talent Hire technical talent

This works best for me

<img src={record.picture} onError={(e)=>{e.target.onerror = null; e.target.src="image_path_here"}}/>

Option to include default image when original src fails to load. · Issue , When there is no image found on the linked src, we could bind onerror to load a default image if provided.? @estrattonbailey Is this by chance  let img = document.createElement('img'); img.src = 'my.jpg'; The browser starts loading the image and remembers it in the cache. Later, when the same image appears in the document (no matter how), it shows up immediately.

You can use uncontrolled component:

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

Fallback image React component, 12. render() {. 13. if (this.state.failed) {. 14. return <img src={this.props.fallbackSrc} />;. 15. } else {. 16. return <img src={this.props.src} onError={this.fallback} />;. Вам нужно просто определить обработчик onError, чем изменить состояние, которое вызовет метод рендеринга компонента, и в конечном итоге компонент будет повторно рендерить с помощью заполнителя.

You need just define onError handler than change the state which will trigger component render method and eventually component will re-render with placeholder.

Please, don't use jQuery and React together!

import React from 'react';
import {Link} from 'react-router';
import ContactStore from '../stores/ContactStore'
import ContactActions from '../actions/ContactActions';

class Contact extends React.Component {
  constructor(props) {
    super(props);
    this.state = ContactStore.getState();
    this.onChange = this.onChange.bind(this); 
 }

componentDidMount() {
  ContactStore.listen(this.onChange);
  ContactActions.getContact(this.props.params.id);
}

componentWillUnmount() {
  ContactStore.unlisten(this.onChange);
}

componentDidUpdate(prevProps) {
  if (prevProps.params.id !== this.props.params.id) {
    ContactActions.getContact(this.props.params.id);
  }
}

onChange(state) {
  this.setState(state);
}

onError() {
  this.setState({
    imageUrl: "img/default.png"
  })
}

render() {
  return (
    <div className='container'>
      <div className='list-group'>
        <div className='list-group-item animated fadeIn'>
          <h4>{this.state.contact.displayname}</h4>
          <img onError={this.onError.bind(this)} src={this.state.imageUrl} />
        </div>
      </div>
    </div>
  );
}

export default Contact;

React OnError Image Component, I tweeted the other day about image onError react component. Image onError Component https://t.co/J4eYM4iyEm @reactjs pic.twitter.com/LZkJl20iJF if Image components src changes, make sure we update origSrc and  Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

Arthur's answer will result in infinite callbacks if fallback image also fails.

To avoid that, first set a state in the constructor for imageLoadError as true :

constructor(props) {
    super(props);
    this.state = {
      imageLoadError: true,
    };
}

and then check for this state value in onError function to avoid infinite callbacks,

the code will look like this :-

<img
    src={"https://if_this_url_fails_go_to_onError"}
    onError={e => { 
        if(this.state.imageLoadError) { 
            this.setState({
                imageLoadError: false
            });
            e.target.src = 'fallbackImage.png';
        }
    }}
/>

react-image, React Image is an tag replacement for react, featuring preloader and multiple image fallback support. Questions: I need to convert my image to a base64 string so that i can send my image to a server. Is there any js file for this… ? Else how to convert it Answers: You can use the HTML5 <canvas> for it: Create a canvas, load your image into it and then use toDataURL()

Error Handling While Use Image Render In React, I am trying to replace the image with a default image if the image does not exist and there is a 404 error. I would normally use the onerror method  React Image is an <img> tag replacement for React.js, featuring preloader and multiple image fallback support. With React Image you can specify multiple images to be used as fallbacks in the event that the browser couldn't load the previous image.

The React debug process will always throw an error while we use image src to <img src="smiley.gif" alt="Smiley face">. ReactJs has the in-built function to render the local image with require ('pathname') in webpack. File From SharePoint REST API In .Net Core · Change Property of Selector in CSS  The easiest way to use react-image is to install it from NPM and include it in your own React build process (using Browserify, etc). You can also use the standalone build by including dist/react-image.js in your page. If you use this, make sure you have already included React, and it is available as

eTour.com is the newest place to search, delivering top results from across the web. Content updated daily for learn react js.

Comments
  • I ran into this problem, and I don't have the code to assist at the moment, but what I did was place the javascript checking in componentdidmount, which looks for an image error, if they occur, a callback is fired which replaces that image with the default image.
  • Please, accept the answer by Georgii Oleinikov, because currently best scored answer may produce eternal loop and so is not good at all.
  • Found this video tutorial on this - youtu.be/90P1_xCaim4 which actually helped me building a full fledged image component for my application. I also found this along with an awesome preloaders for my image component - youtu.be/GBHBjv6xfY4. By combining both you can provide a wonderfull UX for the users.
  • A little note: not working if you're using React with server side rendering because images are being loaded asynchronously and by the time the hydration is made all errors will already have been triggered.
  • Seems like this method could lead to an infinite callback if "image_path_here" produces and error...
  • @tomhughes it will prevent infinite callbacks when "image_path_here" fails
  • @DeepakMallah I followed your code <img src={imageUrl} className={cs.image} onError={(e) => {e.target.src = 'https://upload.wikimedia.org/wikipedia/en/c/c3/The_Martian_2014.jpg'; e.target.onError = null;}} /> However, the console in Safari still shows the error Failed to load resource: the server responded with a status of 404 (Not Found). Is it normal? How to remove this console error? Thanks.
  • Thank you, it works for me! Why isn't the accepted answer?
  • But bootstrap require Jquery bro
  • You shouldn't store state in the <img /> component, but rather in the containing <Image /> component, which would mean refactoring it as a stateful component and using something like this.setState({ src: defaultSrc }).
  • e.target.onerror = null is unneeded. Still, this has to be accepted answer.