6

Coming from reactjs i was expecting "alt" attribute on the image component that will show text in case the image could not be loaded. I read the documentation here and the closest thing I found is the on error event.

Is there an attribute equal to alt in React Native image component? And what is the easiest way to replace your image with a default text if i don't have the alt attribute?

yonBav
  • 1,695
  • 2
  • 17
  • 31

2 Answers2

11

You can make such a component yourself, it requires a very minimal amount of code. Here's a basic example:

export default class AccessibleImage extends Component {

    state = {
        error : false
    };

    _onImageLoadError = (event) => {
        console.warn(event.nativeEvent.error);
        this.setState({ error : true });
    }

    render() {
        const { source, alt, style } = this.props;
        const { error } = this.state;

        if (error) {
            return (
                <Text>{alt}</Text>
            );
        }

        return (
            <Image 
                accessible
                accessibilityLabel={alt}
                source={source} 
                style={style}
                onError={this._onImageLoadError} />
        );
    }
}

This will show the provided alt if there was an error loading the image and also use that text as the accessibilityLabel for screen readers which is closer to web behaviour.

emeraldsanto
  • 4,330
  • 1
  • 12
  • 25
  • 1
    Tnx alot! just wanted to make sure i didn't miss something. I wonder why didn't they add the alt property as default behaviour like in javascript. – yonBav Dec 31 '19 at 14:45
1

A better answer than the previous if using React Native 0.68+ is to include the alt attribute on an <Image> Component like so

      <Image
        style={styles.yourImageStyles}
        source={{
          uri: 'https://reactnative.dev/img/tiny_logo.png',
        }}
        alt={'Alternate text that will be read be screen readers'}
      />
    
Shep Sims
  • 698
  • 9
  • 27