简体   繁体   中英

How to dynamically set react-native image source inside flat list

I'm new to react native i'm trying to populate flat list with images. All the images are stored inside the app. I want to set image source dynamically in every iteration. This is what I tried. Please help me.

<FlatList
  data={this.state.listData}
  renderItem={({ item }) => {
   <Image                                                             
    source={
    (item)=>{
     switch(item.TypeX){
     case '1':
     return require('path 1');
     case '2':
     return require('path 2')
   }
}} />
  }
</FlatList>

You should have images in the data .. in your case in listDate

state = {
  listData: [
  {...,image:require('1.png')},
  {...,image:require('2.png')}
  ...
 ]
}

Then in your render function

<FlatList
  data={this.state.listData}
  renderItem={({ item }) => {
   <Image                                                             
    source={item.image}
}} />
  }
</FlatList>

If you have the images stored in remote url then your state should look like

state = {
      listData: [
      {...,image: 'https://somedomain.com/imagename.png'},
      {...,image: 'https://somedomain.com/imagename2.png'}
      ...
     ]
    }

and in your render function you should use following code

<FlatList
  data={this.state.listData}
  renderItem={({ item }) => {
   <Image                                                             
    source={{uri: item.image}}
}} />
  }
</FlatList>

If you are fetching record from the api you place the request in componentDidMount react callback and set the data using setState function

I think putting switch inside image source prop is not a good idea. Also not sure whether it will work or not. But, you can do one thing..when you are getting data from API that you are filling in your listData array you can append your images' url/path just after getting data from API for eg you receive an array of objects in response:

res=[ { data1:'', data2:''..   },{ data1:'', data2:''.. },{ data1:'', data2:''.. },{ 
   data1:'', data2:''.. }];

so you can iterate the this array and append the images like this:

res.map((obj, i) => { 
   let path = imagepPathArray[i]; 
   return {...obj, imagePath: path  
   }
})

and access image path like this in FlatList:

renderItem={({ item }) => {
   <Image                                                             
    source={{uri: item.imagePath}}
}}

PS: store image paths in separate array first.

I found a soliution , we can create simple function like below in our componet

getFanSpeedImage(speed) {
        switch (speed) {
            case '1':
                return (<Image style={styles.statusButton} source={require('1.png')} />);
            case '2':
                return (<Image style={styles.statusButton} source={require('2.png')} />);
            case '3':
                return (<Image style={styles.statusButton} source={require('3.png')} />);
        }

    }

after that we can call it in out main render function like below

render(){
   return(

<FlatList
  data={this.state.listData}
  renderItem={({ item }) => {
    {this.getFanSpeedImage(item.typeX)}
  }
</FlatList>

);

}

Whenever you have to display images while using Flatlist its good practice if you keep them in an array which you pass as a data to the Flatlist

Hence, first of all, try to structure your data as follows.

 const data = [{ id: 1, name: 'Pikachu', image: require('./path/pikachu.png'), }, { id: 2, name: 'One Plus', image: require('./path/onPlus.png'), }, { id: 3, name: 'Hero Go Pro', image: require('./path/goPro.png'), }, ]

Note the require keyword in the data this will automatically import the required images and now we pass this data to the Flatlist as follows

<FlatList
  showsVerticalScrollIndicator={false}
  data={data}
  renderItem={({item}) => <MyComponent data={item} />} 
  keyExtractor={item => item.id}
  numColumns={2}
  />

Now that we have passed the data to <MyComponent/> it will be accessible in the same component and we can do the following to use it to display the image

<Image source={this.props.data.image} style={{height:20, width:20}}/>

Hope this helps

You can also use https://www.npmjs.com/package/react-native-placeholderimage library.This library helps to put placeholder until your image is not downloaded from internet or API.

renderItem={({item}) =>
    <PlaceHolderImage
    source={!!data.imageurl ? { uri: imgURL } : AppImages.placeHolderImage.source}
    style={iconStyle}
    placeHolderURI={AppImages.placeholderImage.source}
                    />
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM