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

514
Vistas
In React, how can I replace a broken image with a default image?

For example, I have:

<img className="article_link_image" src={article.image}></img>

I also have some JavaScript as follows in a separate file, which detects an image fail and returns either the passing src or a default src.

const image = new Image();

function testImage(url, className) {
  image.onload = imageFound;
  image.onerror = imageNotFound;
  image.class = className;
  image.src = url;
}

function imageFound() {
  return image.src;
}

function imageNotFound() {
  return '/generic.png'
}

testImage('http://example.com/image.png');

module.exports = testImage;

However testImage is asynchronous, and I don't know if is is possible to 'wire' it in to React

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

0

Try something like this

export default function App() {
  const imgToRender = 'https://wrong.com'
  const imgNotFound = 'https://placekitten.com/g/200/300'

  return (
    <div>
      <img
        src={imgToRender}
        alt=""
        onError={e => {
          e.currentTarget.src = imgNotFound
        }}
      />
    </div>
  )
}

or to try something more advance

import { ImgHTMLAttributes } from 'react'

export default function App() {
  return (
    <div>
      <Img
        src="https://wrong.com"
        notFoundSrc="https://placekitten.com/g/200/300"
      />
    </div>
  )
}

interface ImgProps extends ImgHTMLAttributes<HTMLImageElement> {
  notFoundSrc?: string
}

function Img(props: ImgProps) {
  return (
    <img
      {...props}
      onError={e => {
        props?.onError?.(e)

        if (!props.notFoundSrc) return
        e.currentTarget.src = props.notFoundSrc
      }}
    />
  )
}

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