Edward Tanguay
Edward Tanguay

Reputation: 193282

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

I have a React component that will have nearly a hundred images, and so want to load them via one import statement from another JavaScript file.

But first I need to figure out how to put them all in an array somehow so I can export them from that JavaScript file.

Is something like this possible:

enter image description here

So I can access the images like this?

enter image description here

Upvotes: 0

Views: 2276

Answers (1)

MB_
MB_

Reputation: 1747

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>
  );
}

Upvotes: 2

Related Questions