yonBav
yonBav

Reputation: 1915

React Native is there an attribute equals to alt on image component

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?

Upvotes: 7

Views: 9470

Answers (2)

Shep Sims
Shep Sims

Reputation: 1560

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'}
      />
    

Upvotes: 1

emeraldsanto
emeraldsanto

Reputation: 4741

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.

Upvotes: 11

Related Questions