How to Display an Image from an Array of Images in React

How to display an image or multiple images from an array of object to react frontend cart section?

your images are an array so you can't add that as an image source, using React you need to loop and create an img element for each image

change this

<img src={item.images} alt="ssa" />

to something like this:

{item.images.map(image => <img src={image.url} alt="ssa" />)}

Rendering Array of Images in React

You should loop through your images because src expects a string location to the image.

import imagesPool from './imagesPool';

const App = () => {

return (
<div>
{imagesPool.map((imgSrc, index) => (<img src={imgSrc.src} key={index} alt="Make sure to include a alt tag, because react might throw an error at build"/>))}
</div>
)};

How can I create an array of imported images in a React Component?

bulkImages.js v1 (your way is possible)

import image1 from './images/image1.jpg'
import image2 from './images/image2.jpg'
import image3 from './images/image3.jpg'
import image4 from './images/image4.jpg'
import image5 from './images/image5.jpg'


const bulkImages = [
image1,
image2,
image3,
image4,
image5,
];

export default bulkImages;

bulkImages.js v2 (but this version is shorter)

const bulkImages = [
'./images/image1.jpg',
'./images/image2.jpg',
'./images/image3.jpg',
'./images/image4.jpg',
'./images/image5.jpg'
];

export default bulkImages;

To display images from array in your component use the map() function.

YourComponent.js

import React from 'react';

// images data
import bulkImages from './bulkImages';

export default function YourComponent() {
return (
<div className="bulkImageArea">
{bulkImages.map((img) => (
<img key={img} src={img} alt={img} className="bulkImage" />
))}
</div>
);
}

How to display image from variable in react native

Use FlatList to render array of items and it has lazy loading so it will be good when you use large amount of data.

In your case use this code and it will be working fine:

  var [data, setData] = useState([
{
id: 1,
src: require("../assets/image.jpg"),
},
{
id: 2,
src: require("../assets/image2.jpg"),
},
])
return (
<SafeAreaView>
<FlatList
data={data}
showsVerticalScrollIndicator={false}
renderItem={({item}) => (
<Image
source={item.src}
style={styles.imageStyle}
/>
)}
keyExtractor={item => item.id.toString()}
/>
</SafeAreaView>


Related Topics



Leave a reply



Submit