React.Js Replace Img Src Onerror

react.js Replace img src onerror

Since there is no perfect answer, I am posting the snippet I use. I am using reusable Image component that falls back 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 use img onerror

You have onError={this.onError()} with instant function call. It should be either onError={this.onError.bind(this)} or onError={() => this.onError()}.

onError in img tag in React

The code is calling this.onError rather than passing a reference to it. Every call to render is calling this.onError(). Remove the parentheses, and see if that fixes it:

<img className="modalImage" 
src={this.state.imageUrl}
onError={this.onError()}/> // `onError` is being called here

Fixed version:

<img className="modalImage" 
src={this.state.imageUrl}
onError={this.onError}/> // `onError` is being passed as a reference here

React img onError not firing

It's nothing to do with React. Try visiting that url in your browser with a random string for the videoId. It will still display an image - in this case the default youtube thumbnail. So even though it's technically a 404, and your browser will report it as such, the image still has something to display so it won't fire the onError function.

If you replace the url in your code with something that is definitely a 404, your code works fine. Run the snippet below where i've swapped out youtube for google and you'll see your error message.

function onError() {
console.log('errored')
}
<img src="https://img.google.com/vi/some-random-id/maxresdefault.jpg" onError="onError()" />


Related Topics



Leave a reply



Submit