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

296
Vistas
How to show a placeholder image in nextjs image component

I am trying to show images from the API calls. I want to show a placeholder image in case there are no images or any errors. For that, I wrote this code,

const [errorImage, setErrorImage] = useState(null);

  <Image
                            src={`${imageUrl}/${item.image}`}
                            alt="image"
                            layout="fill"
                            objectFit="contain"
                            onError={(e) => {
                              if (!errorImage) {
                                setErrorImage(true);
                                e.target.src = "/static/placeholder.jpg";
                              }
                            }}

But it's not working.

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

0

Changing the state of errorImage when you set it to true will cause the components to re-render, so you don't need to set e.target.src directly.

Option 1 Instead, you can do the following:

const [errorImage, setErrorImage] = useState(null);
const errorImageUrl = "/static/placeholder.jpg";

  const url = errorImage ? errorImageUrl : `${imageUrl}/${item.image}`;
  <Image
    src={url}
    alt="image"
    layout="fill"
    objectFit="contain"
    onError={(e) => {
      if (!errorImage) {
        setErrorImage(true);
      }
    }}

Option 2 Alternatively, you can use the new placeholder prop that was added to <Image> component in NextJS 11. This will show a blurry version of the image you provide.

  <Image
    src={url}
    alt="image"
    layout="fill"
    placeholder="/static/placeholder.jpg"
    objectFit="contain"
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