Dynamic Images with Next.js

Currently, I am utilizing next.js and attempting to dynamically retrieve images in the following manner:

{list.map((prod) => (
      <div className={styles.singleProduct}>
          <h6>{prod.Brand.toUpperCase()}</h6>
          <p>{prod.ProductName}</p>
          <img
              src={require(`../public/assets/products/${prod.ProductName
              .replace(" ", "-")}.png`)}
           /> 
       </div>
  ))}
   

Unfortunately, when implementing this code, I encounter the following error message: "./public/assets/products/Product-One.png 1:0 Module parse failed: Unexpected character '' (1:0)"

In contrast, manually inputting the image path resolves any issues. For example:

... 
<img
    src={require(`../public/assets/products/Product-One.png`)}
/> 
...

I suspect that the error arises due to the dynamic variable. Any assistance in resolving this matter would be greatly appreciated. Thank you!

Answer №1

I encountered a similar issue with svg images, but I found a solution by utilizing the following package: https://www.npmjs.com/package/react-inlinesvg. This package works by dynamically loading the image URL as a data URI and then converting it into an image format (specifically for svg files in this case). Once the conversion is complete, the image is utilized as a react component and inserted as a child element.

Answer №2

After receiving valuable assistance from Alvaro, I was able to find the solution to my problem. The code that ultimately worked is as follows:

src={`/images/items/${item.ItemName.replace(/ /g, "-")}.png`} 

Alternatively, you can use:

src={"/images/items/" + item.ItemName.replace(/ /g, "-") + ".png"} 

I discovered that using "require" with variables caused issues in this scenario.

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

What is the best practice for using templates in a constructor versus connectedCallback?

Should I apply template in the constructor or connectedCallback of a custom element? In my experience, when I apply it in connectedCallback, sometimes attributeChangedCallback is called before and I can't query for elements. export class TestElement ...

Implementing translation functionality within an AngularJs controller

Utilizing angular translate for translating certain words in the controller, with translation stored in json files within the html. // LABELS var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "Septe ...

Conceal Navigation with jQuery

Seeking assistance with jQuery for a new project. I'm trying to create a navigation menu that will automatically disappear after 3 seconds when a user enters the page. In its place, an arrow will be displayed instead of the original menu. Once the a ...

Ways to retrieve the text linked to a checkbox

Is there a way to access the text associated with a checkbox using its attribute? For example, in the code below, I want to alert the user with "Selected -- TextXYZ" when the checkbox is clicked. <form id="idForm" class="classForm"> <input type ...

Listen for a click event on an Unordered List using addEventListener

Struggling to transform a for loop that iterates through an unordered list of hyperlinks and adds an 'onclick' function to each into one using an event listener instead. Unfortunately, I have not been able to create a functional solution. Below ...

What is causing my Next.js application to not generate a build directory when I execute npm run build within the React environment?

I have been facing a challenge with my next.js project as I attempt to use npm run build to compile it for hosting on hostinger. Despite being notified of successful compilation every time I run npm run build, I am unable to locate the folder anywhere. Any ...

Tips for incorporating strikethrough into a drop-down select box in a jquery datatable and implementing filtering based on it

In this scenario, I am currently utilizing a jQuery Datatable with strikethrough text. My aim is to make the filterable dropdown display the same strikethrough text; however, it is not displaying properly at the moment. Below is my jQuery datatable setup: ...

Error Encountered: Custom Login Form Redirecting to https://localhost:3000/api/auth/signin?csrf=true with CredentialsProvider for authentication

PROBLEM STATEMENT: I am encountering an issue while trying to implement a custom login form on my next.js website using next-auth. Whenever I try to log in, it just keeps redirecting me to "https://localhost:3000/api/auth/signin?csrf=true" The server-side ...

Adding a context menu to a Leaflet map

Could someone provide guidance on how to add a custom context menu to a Leaflet map in Vue 3? I am currently utilizing [email protected], @vue-leaflet/[email protected], and experimenting with [email protected]. Here is a snippet of my code: ...

Retrieve information from a JSON file according to the provided input

Can someone help me fetch data based on user input in JavaScript? When the input is 'Royal Python', I'm supposed to retrieve details about it. However, the code provided gives an error stating 'The file you asked for does not exist&apo ...

A guide on integrating MongoDB, Mongoose, Express JS, and Node JS for effectively adding prices

Currently adding various documents to the database: await TestMOdel.insertMany([ { Model: "Samsung", price: 45000, OS: "MS DOS", }, { Model: "Wipro", pr ...

Inquiring about the best method to determine the intersection point between two lines in Draw i.o

Can someone please explain how to find the coordinate point where two lines intersect in draw i.o? I am looking for a Javascript function to solve this issue and get the coordinate of the point only. For example: ...

What is the best way to reveal and automatically scroll to a hidden div located at the bottom of a webpage?

Whenever the image is clicked, I want to display a hidden div with effects like automatically scrolling down to the bottom This is what my code looks like: $(document).ready(function() { $('#test').click(function() { $(&apos ...

After checking the checkbox to add a class, I then need to remove that class without having to interact with the entire document

When I click on a checkbox, an animation is added to a div. However, I am struggling to remove this animation unless I click elsewhere on the document. The goal is for the checkbox to both add and remove the class. JS $('#inOrder').click(functi ...

The <a> tag does not lead to a different webpage and cannot be clicked on

I have developed a web component that includes a method to generate a copyright string: '<p>Copyright © 2020 John Doe<a href="https://www.example.com">. Terms of Use</a></p>' After creating the string, I conver ...

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...

A tool designed to create a function that can fetch information from a JSON file

Currently, I am working on a function that accepts arguments and combines them to form a line for searching data in a JSON file. To accomplish this, I have initialized a variable for the readFileSync and then added the function's arguments to it in or ...

Problems with the duration of Shadcn Toasts (Inspired by the react-hot-toast library)

Within a 13.4 Nextjs project (app router), utilizing Typescript and TailwindCSS. I am currently exploring the usage of toasts provided by the remarkable shadcnUI Library, which draws inspiration from react-hot-toast while adding its own unique flair. Imp ...

What is the most effective method for transmitting a zip file as a response in Azure functions with node.js?

With the Azure function app, my goal is to download images from various URLs and store them in a specific folder. I then need to zip these images and send the zip file back as a response. I have successfully achieved this by following these steps: Send ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...