Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
How to request an image with whichever file extension is available using React?

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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`);
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda