javascript - how to replace src of image while making list in react -
this question has answer here:
- how check broken images in react js 3 answers
could please tell me hhow replace src of image while making list in react? .i have 1 list in there image , it's caption.i want exchange src url in img tag when image not present. if image not present on server want replace src url 1 http://punemirror.indiatimes.com/photo/55813567.cms
if image present on server fine .if not need change source url "http://punemirror.indiatimes.com/photo/55813567.cms "
here code https://codesandbox.io/s/korgkp3b8
i try that
there function detect whether image present or not .but how use function in react ?
imageexists(url, callback) { var img = new image(); img.onload = function () { callback(true); }; img.onerror = function () { callback(false); }; img.src = url; }
you can create component handle logic you:
class smartimage extends react.component { constructor() { super(); this.state = { fallback: true }; } componentdidmount() { this.checkimage(); } componentdidupdate(prevprops) { if (prevprops.image !== this.props.image) { this.checkimage(); } } checkimage() { let img = new image(this.props.img); img.onload = () => { this.setstate({ fallback: false }); }; img.onerror = () => { this.setstate({ fallback: true }); }; } render() { return ( <img src={this.state.fallback ? this.props.imgfallback : this.props.img} /> ); } } and instead of rendering img tags directly, you'd render smartimage components this: <smartimage img={url1} imgfallback={url2} />
it checks if image loaded each time changed, , on mount, , changes state accordingly, renders accordingly.
Comments
Post a Comment