0

i am making a react app if the src isn't valid i replace it with a default image now sometimes a image with a valid src doesn't load from the server cuz it's not found (404) i searched on internet and tried these:

<img onError={this.src="https://image.defaul-img.jpg"} src={!imgURL ? "https://image.defaul-img.jpg" : imgURL} className="card-img-top" alt="..." />

and

<img src={!imgURL ? "https://image.defaul-img.jpg" : imgURL} className="card-img-top" alt="https://image.defaul-img.jpg" />

but none of them work what can i do

Curious
  • 43
  • 6
  • The purpose of the 'onerror' event is perform an operation when a resource such as image urls to trigger when it fails to load. If the purpose of your 'imgURL' variable is for checking if the image is valid, you don't have to perform a ternary condition in this case since you have a default image to fallback on. Also, what is the purpose of the '!imgURL' ternary condition? are you checking for empty strings? – Ibaboiii Feb 04 '23 at 16:06
  • ` { e.target.onerror = null; e.target.src = "https://image.default-img.jpg"; }} className="card-img-top" alt="..." />` – NIKUNJ PATEL Feb 04 '23 at 16:25

2 Answers2

0

this code works i find it on stack overflow sorry i will not post a question before properly researching again

<img onError={({ currentTarget }) => {
    currentTarget.onerror = null; // prevents looping
    currentTarget.src = "https://image.defaultimg.jpg";
                }} src={!imgURL ? "https://image.defaultimg.jpg" : imgURL} className="card-img-top" alt="..." />
Curious
  • 43
  • 6
0

Create a ref for img element and handle fallback cases,

import { useRef } from "react";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <Image src="/me.png" fallback="https://source.unsplash.com/random" />
    </div>
  );
}

function Image({ src, fallback }) {
  const ref = useRef();

  function handleFallback() {
 // Nullify the error event for subsequent calls
    ref.current.onError = null;
    ref.current.src = fallback;
  }

  return <img alt="My img" ref={ref} src={src} onError={handleFallback} />;
}

For vanilla.js version of the handling :How does one use the onerror attribute of an img element

Mallikarjun M G
  • 509
  • 4
  • 9