Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

513
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!