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

Why is Axios not being successfully registered as a global variable in this particular Vue application?

Recently, I have been delving into building a Single Page Application using Vue 3, TypeScript, and tapping into The Movie Database (TMDB) API. One of the hurdles I faced was managing Axios instances across multiple components. Initially, I imported Axios ...

Easy-to-use blog featuring Next.js 13 and app router - MDX or other options available

Currently in the process of transitioning a Gatsby website to Next.js (v13.4) and utilizing the new App Router. However, I'm facing some challenges when it comes to migrating the blog section over because there isn't much accurate guidance availa ...

Value returned by Typescript

I have been attempting to retrieve a string from a typescript function - private _renderListAsync(): string { let _accHtml: string=''; // Local environment if (Environment.type === EnvironmentType.Local) { this._getMockLi ...

"Unlocking the power of MongoDB with Next.js: A step-by-step guide to

Feeling lost while trying to establish a connection to my mongodb database in the latest version of Nextjs. The changes have left me confused about what steps to take next. For guidance on setting up the connection, check out this example: https://github. ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

PersistGate gets stuck in a loading state when a query parameter is detected in the URL

I have been experimenting with the with-redux-persist repository in conjunction with next.js, which can be found at this link: https://github.com/vercel/next.js/tree/canary/examples/with-redux-persist One issue I encountered is that when using a custom lo ...

Unleash the power of Typescript and Node to create detailed REST API documentation!

Is it possible to generate REST API documentation using https://github.com/TypeStrong/typedoc similar to what can be done with ? I would appreciate any recommendations on leveraging TypeScript types for creating REST API documentation (specifically within ...

"Upon invoking the services provider in Ionic 2, an unexpected undefined value was

I encountered an issue while setting a value in the constructor of my page's constructor class. I made a call to the provider to fetch data. Within the service call, I was able to retrieve the data successfully. However, when I tried to access my vari ...

Adjusting an item according to a specified pathway

I am currently working on dynamically modifying an object based on a given path, but I am encountering some difficulties in the process. I have managed to create a method that retrieves values at a specified path, and now I need to update values at that pa ...

How can I correctly display an error message in NextJS 13.4 API using Response, NextAPIResponse, or NextResponse?

In the past, handling errors in the APIs was done as shown below. if (error) { return response .status(500) .json({ error: 'Error getting data from Supabase' }); It used to work when the response was a NextAPIResponse object t ...

Using TypeScript to send state through history.push({...})

I recently utilized the history.push method to redirect to a specific URL while passing along some information through the included state. Here's how I implemented it: const history = useHistory() history.push({ pathname: '/someurl/', ...

Tips for including a JWT token as a query parameter in NEXT js?

const UserJwt = (props) => { const { jwt } = props; const [jwtToken, setJwtToken] = useState(null); useEffect(() => { if (jwt) { setAuthToken(jwt); setJwtToken(jwt); } }, [jwt]); return <MobilePurchaseScreen {...pro ...

Extending the Object prototype within an ES6 module can lead to errors such as "Property not found on type 'Object'."

There are two modules in my project - mod1.ts and mod2.ts. //mod1.ts import {Test} from "./mod2"; //LINE X interface Object { GetFooAsString(): string; } Object.prototype.GetFooAsString = function () { return this.GetFoo().toString(); } //mod2. ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

Typescript is throwing an error with code TS2571, indicating that the object is of type 'unknown'

Hey there, I'm reaching out for assistance in resolving a specific error that has cropped up. try{ } catch { let errMsg; if (error.code === 11000) { errMsg = Object.keys(error.keyValue)[0] + "Already exists"; } return res.status ...

There seems to be an issue with the Next.js build as it encountered errors while exporting on

I encounter this error during the build process. info - Generating static pages (15/15) > Build error occurred Error: Export encountered errors on following paths: /routine/RoutineLists at /home/corepen/Desktop/Project 1/rouDDine-client/no ...

combine string inputs when ng-click is triggered

Is there a way to pass a concatenated string using ng-click to MyFunction(param: string)? I have tried but so far, no luck: <input id="MeasurementValue_{{sample.Number}}_{{$index}}" ng-click="Vm.MyFunction('MeasurementValue_{{sample.Number ...

The Sign-In Error in Firebase is Concealing the True Issue in useSignInWithEmailAndPassword function within a React Web Application Project

I am facing an issue with throwing an error when attempting to register an account with a previously used email using TypeScript, Firebase, and React. Despite successfully registering an account, the problem arises when I try to use the same email with a d ...

Tailwind doesn't just apply styles in a traditional manner

I am facing an issue where Tailwind CSS is not applying styles in my file, but it works perfectly fine in page.tsx. I am using NextJS with Tailwind. I have a component Menu.tsx declared as : export default function Menu() { return <div className=&quo ...

What is the reason for the retrieval of jquery-3.5.1.min.js through the request.params.id expression?

For my school project, I am using Express.js with TypeScript to create a simple app. This router is used for the edit page of a contact list we are developing. It displays the ID of the current contact being edited in the search bar. The problem arises whe ...