Search code examples
react-nativereact-native-imagereact-native-component

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?


Solution

  • 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.