I'm trying to import images into a list dynamically. some images are missing, so I did a try catch to check if the image exists, otherwise I have one by default.
const setSource = (src) =>{
const imgTMP = dirImg + src + ".jpg";
try{
require(imgTMP)
// console.log('ok', src);
return imgTMP;
}
catch(err){
// console.log('none', src);
return "../../assets/artwork/h.jpg";
}
}
<Artwork.Thumbnail>
<img
src= {require(setSource(art.id).toString())}
alt='art'/>
</Artwork.Thumbnail>
the concern is that the try/catch refuses to work properly.
moreover the character string returned (even valid) returns an
Uncaught Error: Cannot find module
Thanks for your help
fixed by this class:
import React from "react";
//Lazy loading images
//PROPS: src, alt, className, onError, unloadedSrc
//?props: onError : directory of the image if not found
//?porps: className : className of the image
//?props: alt: alt of the image
//?props: src : src of the image
//?props: unloadedSrc : src of the image not loaded
export class LazyImage extends React.Component {
constructor(props) {
super(props);
this.state = {
loaded: false,
error: false
};
}
componentDidMount() {
const img = new Image();
img.onload = () => {
this.setState({
loaded: true
});
};
img.onerror = () => {
this.setState({
error: true
});
};
img.src = this.props.src;
}
render() {
if (this.state.error) {
return <img
className={this.props.className}
style={this.props.style}
src={this.props.unloadedSrc}
alt={this.props.alt} />
} else if (!this.state.loaded) {
return <img
className={this.props.className}
style={this.props.style}
src={this.props.unloadedSrc}
alt={this.props.alt} />
}
return <img
className={this.props.className}
style={this.props.style}
src={this.props.src}
alt={this.props.alt} />
}
}