Home > OS >  url path with image variable in image source uri React Native
url path with image variable in image source uri React Native

Time:02-10

I am trying to display an Image in which the data was fetch from an api and render into a flatlist, I am trying to concat or connect the sting link with the variable, in the image source uri but did not work, how can I fix it.

<FlatList 
data = {data}
keyExtractor={item => item.id}
showsVerticalScrollIndicator = {false}  
renderItem={({item}) => {
   return (

    <Image 
            source={{ uri: `https://placewave.com/avatar/${item.user_image}` }}
            resizeMode="cover"
            style={styles.userImage}
    /> 

   )
}}
/>

Thanks for the help

CodePudding user response:

Unfortunately it will not work in such way. Image must not have conditional source prop. Consider moving https://placewave.com/avatar/${item.user_image} to a variable and add condition to display some kind of fallback(like ActivityIndicator) until you will have valid user_image.

CodePudding user response:

Complete test code

import * as React from 'react';
import { Image, Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  const data = [{ id: 1, user_image: 'cute-boy-standing-little-white-background-40214306.jpg' }, { id: 1, user_image: 'no image url.jpg' }]
  return (
    <View >
      <FlatList
        data={data}
        keyExtractor={item => item.id}
        showsVerticalScrollIndicator={false}
        renderItem={({ item }) => {
          let uriVar
          if (item.user_image) uriVar = `https://thumbs.dreamstime.com/b/${item.user_image}`
          return (<View>
            {uriVar != null ?
              <Image source={{ uri: uriVar }}

                style={styles.userImage}
              /> : null} </View>)
        }}
      />
      <Text style={styles.paragraph}>
        Hello
      </Text>

    </View>
  );
}

const styles = StyleSheet.create({
  userImage: {
    width: '150px',
    height: '150px',
    borderWidth: 1
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});
  • Related