Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

523
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda