reactjsreact-nativereact-native-flatlistimagebackground

How to set onError on images in react native inside flatlist


I have a page where I list people with their info. I have used Flatlist for rendering the n number of data that I am getting and also for pagination.

<FlatList
    showsVerticalScrollIndicator={false}
    data={this.state.records}
    keyExtractor={(item) => String(item.ServiceRequestID)}
    renderItem={({ item }) => (
    <View>
    <ImageBackground
    source={{ uri: this.state.baseUserImagePath + item.ImagePath }}
    style={styles.image}
    imageStyle={{ borderRadius: h2p(48) }}
    />
    //other parts
    </View>
    )}
    onEndReached={()=>{//logic}}
    />

I wish to load default user image for images that fail to load (deleted in local server in my case). So, I want to add the onError property in the imagebackground. For a single image I can use

onError={() => {this.setState({ image: require('../../assets/user.png') });}} and use source={this.state.image}

How can I do this for images inside Flatlist to handle my case.


Solution

  • We can create a separate component and use it in the flatlist renderItem function.

    like:

    const FlatListComponent = props => {
    
        const [isError, setError] = useState(false)
    
        return (
            <View>
                <ImageBackground
                  source={isError ? require('show-defaultImage') : { uri: props.image }}
                  style={styles.image}
                  imageStyle={{ borderRadius: h2p(48) }}
                  onError{(e) => setError(true)}
                 />
                //other parts
            </View>
        )
    
    }
    

    FlatList Code

    <FlatList
        showsVerticalScrollIndicator={false}
        data={this.state.records}
        keyExtractor={(item) => String(item.ServiceRequestID)}
        renderItem={({ item }) => (
            <FlatListComponent 
                 image={this.state.baseUserImagePath + item.ImagePath}
            />
        )}
        onEndReached={()=>{//logic}}
    />