Issue with making a call to retrieve an image from a different directory in ReactJS

This is how it appears

<img className='imgclass' src={"../" + require(aLc.value)} alt='' key={aLc.value} />

I am trying to create a path like ../m/b/image.jpg, where aLc.value contains the path /m/b/image.jpg. I need to add only .. before the folder path, but it is not working. I attempted to do it as shown in the example above, but it gives me the error message:

Error: Cannot find module '/m/b/image.jpg'
. I also tried the following:

<img className='imgclass' src={require(".." + aLc.value)} alt='' key={aLc.value} />

However, this results in an error saying: Error: Cannot find module "."

How can I resolve this issue?

@edit - Resolved with Map function

const ProductsList = ({ data: {loading, error, allLinks }}) => {
  if (loading) {
    return <p>Loading ...</p>;
  }
  if (error) {
    return <p>{error.message}</p>;
  }

  return (
    <div className="productList">
        <div className="container">
            <div className="row">
        {
            allLinks.items.map( aL =>
            <div key={aL.id} className="product">

            {
                aL.custom_attributes.map( aLc =>

                    aLc.__typename === 'CustomString' && aLc.attribute_code === 'image'

                        ? <img className='imgclass'  src={require(`../components${aLc.value}`} alt='' key={aLc.value} />  //without subordinate folder 'components' react auto delete one of dots e.g (require(`..${aLc.value}`) => Error: Cannot find module '.' because react deleted one dot.
                    :  aLc.__typename === 'CustomString' && aLc.attribute_code === 'description'
                        ? <div key={aL.id}>{aLc.value}</div>
                    :  aLc.__typename === 'CustomArray'
                        ?   aLc.aliasVar.map( aV => <div key={aV}>{aV}</div>)
                    : null


                )

            }
            </div> )
        }
            </div>
        </div>
    </div>
  );
};

allLinks represents the type name of the API. All values are present in the API.

Answer №1

To implement this, you just need to include the following code:

<img className='imgclass' src={`../${aLc.value}`} alt='' key={aLc.value} />

This should be effective in achieving the desired outcome.

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

A caution about using componentWillMount with functions that update state is important to consider

I am facing an issue with a clear button in my render method. <Button onClick={this.clearFilters(data)}> CLEAR </Button> The button is supposed to call a function that clears out a state. clearFilters(data){ if (!data || !this.state) { ...

Generate spacing between rows of content in HTML or CSS without affecting the spacing between lines of text

In my R Markdown document in R, I want to replace the header labeled "Preface" with grey lines for visual indication. Here's the code snippet I've tried: :::{#preface} <p> Text </p> ::: However, there seems to be no margin at the beg ...

Dealing with a section that won't stay in place but the rest of the webpage is

I recently came across the angular-split library while trying to address a specific need. It partially solved my problem, but I still have some remaining challenges. In my setup, I have divided my content into 2 sections using angular-split. The goal is f ...

Trouble with ScrollTo animation on div with adjustable offset top feature - seeking assistance

Having trouble navigating to the correct slide when clicking the right button on the navigation menu. Clicking the menu button displays a list of links. Clicking on a link for the first time will take you to the correct slide, but if you try clicking a dif ...

Are there any tools available that can convert inline styles into CSS classes?

Can anyone recommend a package that will transform this text: <p style="width: 500px; height: 500px"> Hello World </p> into this format: <p class="foo"> Hello World </p> .foo { width: 500px; height: 500px; } ...

Back from the depths of the .filter method encased within the .forEach

I have been working on this code and trying to figure it out through trial and error: let _fk = this.selectedIaReportDiscussedTopic$ .map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) .forEach((fk) => { ...

Expanding iFrame width in Drupal 7

I'm grappling with how to create a full-width page in my Drupal 7 website. This specific page contains an embedded form. Initially, there were two blocks on the page that I removed in hopes of getting the iframe to expand to fill the space. The cur ...

What is the best way to get a string as a return value from an async function that uses the request API

I'm currently working on a project that involves printing the HTML code source as a string using the request API. I've created a function to fetch the data as a string, but when I try to print the output, it returns undefined. I'm struggling ...

Css shaky letters transformation

[SOLUTION] To resolve this issue, you can utilize the will-change CSS property that enforces GPU rendering: will-change: transform; [ORIGINAL QUESTION] After extensive searching on the internet, I have yet to find a solution to a seemingly simple prob ...

``Enhance your website with stunning Bootstrap 4 image cards that beautifully showcase

I'm having trouble creating 3 simple image cards with captions in Bootstrap 4. No matter what I do, the image keeps taking up the entire card and covering the caption below it. My cards should look similar to Bootstrap's example card, using the ...

The validation in React seems to be malfunctioning when used in conjunction

Currently, I am receiving data from the backend through a socket connection. The data (item) is then pushed to an array. However, if a certain variable is set to true (indicating that it's paused), I do not want to push the item to the array. cons ...

The alignment of my text appears to be off

I am facing an issue with the second <ul> on my webpage, which contains more content compared to the first one. In this second <ul>, the last line is appearing floated to the left and does not appear below the penultimate line as expected. Li ...

Bringing in functions - NodeJS - non-HTML

Currently, I am in the process of learning automation for my job and have hit a roadblock. In times like these, stackoverflow has proven to be a life-saving resource :) My current task involves writing a Selenium test in VisualStudio using JavaScript (nod ...

Experiencing difficulty retrieving the variable within a NodeJs function

Currently, I am utilizing the NodeJS postgresql client to retrieve data, iterate through it and provide an output. To accomplish this, I have integrated ExpressJS with the postgresql client. This is a snippet of my code var main_data = an array conta ...

Ways to prevent websites from switching to landscape mode

Is there a way to prevent landscape mode on my website and restrict users to portrait mode, especially for devices with screen widths below 777px? I have custom headers that take up fixed position space of around 100px on the screen. If it is possible to ...

Dynamic filtering of items using Knockout's foreach binding based on value change

I'm working on some HTML/Knockout code where I want to display a dayDivider div only when there is a new date. This means that messages from the same day should appear under a date banner. Typically, I would save the last value in a temporary variable ...

Discover the best way to reference a JavaScript variable within an HTML form textfield

I'm having trouble with a script that is supposed to display the selected value from a drop down list in a text field on an HTML form. When I select an option, the value is not appearing in the text field. Can someone please assist me with this issue? ...

Raising the css value for each element that is impacted

I am faced with an infinite number of elements that I need to arrange next to each other. Each element has a class called "box". My goal is to separate each box by 10px increments, meaning the first element will have a left property of 0px, the second 10px ...

Changing all object values to true with React useState

In a certain file, I have defined an object with the following structure: export const items = { first: false, second: false, third: false } Within a component, I am using this object as shown below: import { items } from 'file'; const [el ...

It appears that the jQuery.post() method is being overlooked or bypassed for unknown reasons

Trying to understand why the call to jQuery.post() isn't fetching the data or running the function after the fetch. Three files are included: an HTML file, a JavaScript file, and a PHP file. The HTML contains the modal element intended to appear when ...