explore and view all images within a directory

Hello, I am new to NextJS and encountering some issues. I have a folder in my public directory containing 30 images that I want to import all at once in the simplest way possible, without having to import each image individually by name. Here is the current code snippet:

import Image from 'next/image'

// Importing all 30 images
...

import styles from './styles.module.scss';

/**
 * @function Album
 * @access Public
 * @description Component
 */
export function Album() {
    const allImages = [
        // List of imported images
    ];

    const imgWidth = 5;

    return (
        & lt; section className={`ececec`}>
            <div className={styles.horizontalScroll}>
                <div className="d-flex justify-content-between" style={{ width: `${(imgWidth + 0.625) * allImages.length}rem` }}>
                    {allImages.map((item, index) =& gt; {
                        <Image className={styles.img_contractor} src={item} width="120" height="120" alt={`Album ${index + 1}`} objectFit="cover" />
                    })}
                    <Image className={styles.img_contractor} src={album_01} width="120" height="120" alt={`Album 01`} objectFit="cover" />
                </div>
            </div>
        </section>
    );
}

The issue is that only one image is showing on the page:

<Image className={styles.img_contractor} src={album_01} width="120" height="120" alt={`Album 01`} objectFit="cover" />

I'm unsure of what I might be missing here. Any advice or suggestions are appreciated!

Answer №1

function loadImages(path) {
  let gallery = {};
  path.keys().map((item, index) => { gallery[item.replace('../../public/imgs/myfolder','')] = path(item); });
  return gallery;
}

const gallery = loadImages(require.context('../../public/imgs/myfolder', false, /\.(png|jpe?g|svg)$/));

<Image className={styles.img_contractor} src={gallery.album01} width="120" height="120" alt={`Album 01`} objectFit="cover" />

Here's another way you could approach this.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connecting to a fresh dynamic route does not impact the getInitialProps data

I am struggling to understand the difference between componentDidMount and getInitialProps. Despite my best efforts to research, I still can't figure out when to use each one in my specific case. Let me give you some context. I have a page called /co ...

Can you provide guidance on integrating this jQuery script into my Next.Js application effectively?

I have been using a script on a plain HTML website, importing it via the <script> tag: (function($) { var wa_time_out, wa_time_in; $(document).ready(function() { $(".wa__btn_popup").on("click", function() { if ($(&qu ...

A guide on utilizing getStaticProps to map a collection obtained from Strapi within a Next.js component

I'm currently following a tutorial on YouTube that teaches how to create a basic blog using Next.js and Strapi. The code snippet below is used to fetch post data from Strapi, but it's not working as expected because the .map function can only be ...

Challenges when building a production version of an Expo app with Typescript

Attempting to perform a local production build, I ran expo start --no-dev --minify. Only the initial template file displays, stating "Open up App.tsx to start working on your app," and none of my work is visible... Has anyone else encountered this issue a ...

Embark on a journey through a preorder traversal of a Binary Tree using TypeScript

Hello! I've been tasked with creating a function that iterates over a binary tree and returns all its values in pre-order. Here is the code snippet: interface BinTree { root: number; left?: BinTree; right?: BinTree; }; const TreePreArray ...

Issue: Expressjs is throwing a TypeError due to an attempt to read the 'id' property of undefined

I am currently working on a registration function in expressjs, but I keep encountering the following error message: TypeError: Cannot read properties of undefined (reading 'id') This is my user model: Users.ts interface UserAttributes { id: ...

Using React with Next.js, I experienced a strange issue where the useOutsideClick hook was interfering with

I have implemented a hook to handle the "click away" feature for showing/hiding a dropdown: const useOutsideClick = (ref: NonNullable<RefObject<HTMLButtonElement>>) => { const [outsideClick, setOutsideClick] = useState<boolean | null> ...

Guide to Integrating NextAuth(v5) with Next-Intl Middleware in Your Next.js Application

I'm currently developing a Next.js application that relies on NextAuth(v5) for authentication and Next-Intl for internationalization. I am looking to seamlessly integrate these two functionalities. Here's what I have attempted so far: Current Mi ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

Is there a sophisticated method for breaking down a nested property or member from TypeScript imports?

Just curious if it's possible, not a big deal otherwise. import * as yargs from 'yargs'; // default import I'm looking to extract the port or argv property. This would simplify the code from: bootstrap(yargs.argv.port || 3000) to: ...

What is the process for defining a recursive array data structure?

Looking to implement a TypeScript method that can navigate through nested arrays of strings when given an instance of a type/class/interface. The method, in concept, should resemble: method<T>(instance: T, arrayAttr: someType) { let tmp = undefin ...

Issue with Angular data display in template

My Ionic app with Angular is fetching data in the constructor, but I am facing difficulties displaying it in the HTML. Code component receiver: any; constructor( //.... ) { // get receiver data const receiverData = this.activatedRoute.snapsho ...

Initiate the input change event manually

Struggling with creating a custom counter input component where the input value is controlled by custom increment/decrement buttons. Desired output: https://i.sstatic.net/oYl1g.png Content projection will be used to expose the input for form usage and a ...

Why aren't enums that can be derived supported?

Is there a way to create an enum that is a subset of another enum? Sometimes it would be useful to have an enum that is a subset of another Enum with the same values at run time but under a different name. Are there better ways to handle this scenario? ...

The Next.js 404 error page seems to be malfunctioning. Any ideas on what might be causing this issue?

Whenever I attempt to access a non-existent route, the home page loads without changing the URL. My expectation was to see a 404 error page. To handle this issue, I created a custom error page called pages/_error.js import Page404 from './404'; ...

Adding custom CSS and JavaScript to an Angular 4 project can be done by including the necessary

When working with Angular 2, I was able to include stylesheets directly in the index.html like so: <link rel="stylesheet" href="css/mycss.css"> However, with Angular 4, the styles need to be added to the angular-cli.json file within the styles and ...

strategies for chaining together multiple observables with varying data types and operations

Hey everyone! I'm facing a situation where I have a form with multiple select types, and the options for these inputs are coming from an API. I then take the data emitted from the HTTP request observable and feed it into my FormGroup, and everything i ...

Tips for transforming a string into a variable within an Angular framework

I'm working with a JSON object retrieved from an API let arr = [{"name": 'abc',"age": '23'},{"name": 'qwe',"age": '37'},{"name": 'wqewqe',"age&quo ...

Angular2: Promise Rejection: Quotes cannot be used for evaluation in this component

I'm currently working on a component in Angular that includes an input parameter: import {Component, Input} from '@angular/core'; @Component({ selector: 'comment', template: ` <div class="col-lg-6 col-md-6 ...

Encountering issues with Nextjs routes not functioning properly after deployment on an Azure App Service Linux Instance

I recently tried to deploy a next.js app on Azure App Service using a Linux instance. I followed the guidelines provided in this helpful article: . The live version of the app can be accessed at as well as . The routes function correctly on Heroku. For ex ...