Search code examples
javascripthtmlreactjs

Show a default image if src image is not found


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


Solution

  • 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="..." />