I need to load an image file and I'm trying to write a short code to just get whatever version is available (first .svg and if not available then .png), so I came up with this React snippet:
Apologies in advance for butchering code formatting and possibly other beginner's mistakes
let serviceLogo = (typeof this.props.service != undefined || typeof this.props.service != "undefined" )
?
(
require( `./path/logo-` + this.props.service + `.svg`) != null
? require(`.path/logo-` + this.props.service + `.svg`)
: require(`.path/logo-` + this.props.service + `.png` )
)
: "" ;
which will then just be called here
<img src={serviceLogo} />
It works fine if the file is .svg. But I'm missing something because if the image file extension is .png instead I get the error:
Uncaught Error: Cannot find module './logo-whateverfilename.svg'
How can I fix the code to give me a PNG file if an SVG version doesn't exist?
It gives an error because require is trying to import file that doesn't exists before you check if that file exists or not.
require( `./path/logo-` + this.props.service + `.svg`) != null
you can try to encapsulate your code with try catch like this
let serviceLogo = '';
if (this.props.service) {
try {
serviceLogo = require( `./path/logo-` + this.props.service + `.svg`);
} catch (error) {
serviceLogo = require( `./path/logo-` + this.props.service + `.png`);
}
}