Home > Enterprise >  React Native - Map over image sources into Image Component
React Native - Map over image sources into Image Component

Time:01-25

I've got the following sample array of images:

const images = [
    {
      source: './a.png',
    },
    {
      source: './b.png',
    },
    {
      source: './c.png',
    },
    {
      source: './d.png',
    },
    {
      source: './e.png',
    },
    {
      source: './f.png',
    },
    {
      source: './g.png',
    },
  ];

When I try to map over each image into an Image component, I think the source property is not being loaded correctly because the Image component remains empty.

Is there any work around for this?

{images.map((image) => {
    <Image
       source={image.source}
       style={{
         width: 100,
         height: 180,
       }}
    />

CodePudding user response:

You need to set image source for local files using require like this:

const images = [
    {
      source: require('./a.png'),
    },
]

You can check this working example from here

import { Image, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  const images = [
    {
      source: require('./assets/snack-icon.png'),
    },
    {
      source: require('./assets/snack-icon.png'),
    },
    {
      source: require('./assets/snack-icon.png'),
    },
    {
      source: require('./assets/snack-icon.png'),
    },
  ];
  return (
    <View style={styles.container}>
{images.map((image) => 
    <Image
       source={image.source}
       style={{
         width: '100%',
         height: 180,
         resizeMode: 'contain',
         marginBottom: '2%'
       }}
    />)}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});
  • Related