Josh
Josh

Reputation: 1089

Show alt text for image even if src fails

I have a list of images, all that use dynamic URLs. If the URL fails, I can disable the broken image icon, which is great. But I'd like to still be able to show the alt text in its place.

Here is what I'm working with right now:

<img 
  src = {'abrokenimage'} 
  width = {100} 
  height = {100}
  alt = {'I want this to display even when image src fails...'}
  onError = {(thisImage) => {thisImage.target.style.display='none';}}
/> 

How can I not show the broken image icon, but still show the alt text?

Upvotes: 0

Views: 326

Answers (1)

duc mai
duc mai

Reputation: 1422

my best solution is to create an image component to handle that

import React, { useState } from 'react';

const Image = (props) => {
  const [isError, setError] = useState(false);
  return !isError ? (
    <img {...props} onError = {() => setError(true)} />
  ) : (<span>props.alt</span>);
}

Upvotes: 1

Related Questions