0

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

1 Answer 1

2

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>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.