React.js Replace img src onerror

Asked
Active3 hr before
Viewed126 times

11 Answers

onerrorreplacereact
90%

Since there is no perfect answer, I am posting the snippet I use. I am using reusable Image component that fallbacks to fallbackSrc.,Try this custom Image component:,Arthur's answer will result in infinite callbacks if fallback image also fails.

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,
};
load more v
88%

Remember, if you want to change the styles of the element and/or change the img source, just do something like this:

<img
  src={'original src url goes here'}
  alt="example"
  onError={(e) => {
     e.target.src = '/example/noimage.png' // some replacement image
     e.target.style = 'padding: 8px; margin: 16px' // inline styles in html format
  }}
/>
72%

This works best for me

This works best for me

<img src={record.picture} onError={(e)=>{e.target.onerror = null; e.target.src="image_path_here"}}/>
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,
};

You can use uncontrolled component:

<img src={this.state.img} ref={img => this.img = img} onError={
    () => this.img.src = 'img/default.img'
}>
load more v
65%

Let’s get back to broken images. The most basic approach would be to use the onError event and replace an image that failed to load with a fallback image. It’s supported by all browsers (compatibility report here).,The Ant Design carousel did use the standard IMG html image element. That allowed me to do a callback onError, and pass the key of the broken image.,In React we can also use onError, and trigger a function that can deal with it the broken image.

Let’s get back to broken images. The most basic approach would be to use the onError event and replace an image that failed to load with a fallback image. It’s supported by all browsers (compatibility report here).

<img src="image.png" onError="this.onerror=null; this.src='/images/noimage.gif';" />
load more v
75%

I have a react component that is the detail view from a list.,react.js Replace img src onerror ,I am trying to replace the image with a default image if the image does not exist and there is a 404 error.

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;
load more v
40%

 Pretag team - issue, fix, solve, resolve
22%

 Pretag team - issue, fix, solve, resolve
60%

У меня есть компонент react, который представляет собой подробное представление из списка. , заменить значение img src , Нужно заменить img src шаблоном кода

Вот мой компонент:

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;
load more v
48%

 Pretag team - issue, fix, solve, resolve
23%

The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).,Execute a JavaScript if an error occurs when loading an image:,Tip: When used on audio/video media, related events that occurs when there is some kind of disturbance to the media loading process, are:

 Pretag team - issue, fix, solve, resolve
90%

页面在加载图片的时候,如果图片资源不存在,为了更好的用户体验,我们一般会用一张默认图片替换,提醒用户当前图片缺失。 但还有一种情况是图片地址存在,只是图片地址出错了返回了404错误,这时也需要使用一张默认图片替换。 然而我们的设计师给我的是一个SVG文件,SVG文件我们都是封装成组件的形式调用,所以我无法生成一个图片链接替换。 在参考了以下链接后,我动手写了一个组件。 https://stackoverflow.com/questions/34097560/react-js-replace-img-src-onerror

 Pretag team - issue, fix, solve, resolve

Other "onerror-replace" queries related to "React.js Replace img src onerror"