Utilize React JS to dynamically render JSON array of images onto a JSX page in React

state = {
  products: [
    {
      img: "'./images/heartstud.jpg'",
      name: "Heart Earrings",
      price: "1.99",
      total: "3.98",
      count: 2,
      description:
        "Yellow Chimes Crystals from Classic Designer Gold Plated Stylish Hoop Earrings for Women and Girls",
    },
    {
      img: "./images/heartstud.jpg",
      name: "Orange",
      attribution: "visualhunt",
      price: "0.99",
      count: 1,
      description:
        "PANASH Woman's Stylish/Fashion Gold-plated Beaded Handcrafted Chandbalis Trendy Party/Festive/Wedding Wear Earrings",
    },
    {
      img: "./images/heartstud.jpg",
      name: "Pear",
      price: "6.00",
      count: 4,
      description:
        "Valentine Gift By Shining Diva Italian Designer Non Precious Metal Jewellery Set for Women",
    },
  ],
};

This HTML code allows me to display product images, names, prices, and descriptions dynamically based on the data stored in the 'products' array within the state.

<div class="row">
  {this.state.products.map((product) => (
    <div class="col-lg-4 col-md-6 mb-4">
      <div class="card h-100">
        <a href="#">
          <img class="card-img-top" src={require("./images/ring.jpg")} alt="" />
        </a>
        <div class="card-body">
          <h4 class="card-title">
            <a href="#">{product.name}</a>
          </h4>
          <h5>${product.price}</h5>
          <p class="card-text">{product.description}</p>
        </div>
      </div>
    </div>
  ))}
</div>;

Currently, I am unable to dynamically fetch the product image using {product.img} due to restrictions with the require function. Any assistance or suggestions on how to resolve this would be greatly appreciated.

Answer №1

class ShoppingApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [
        {
          img: "https://via.placeholder.com/600/92c952",
          name: "Heart Earrings",
          price: "1.99",
          total: "3.98",
          count: 2,
          description:
            "Yellow Chimes Crystals from Classic Designer Gold Plated Stylish Hoop Earrings for Women and Girls"
        },
        {
          img: "https://via.placeholder.com/600/771796",
          name: "Orange",
          attribution: "visualhunt",
          price: "0.99",
          count: 1,
          description:
            "PANASH Woman's Stylish/Fashion Gold-plated Beaded Handcrafted Chandbalis Trendy Party/Festive/Wedding Wear Earrings"
        },
        {
          img: "https://via.placeholder.com/600/771766",
          name: "Pear",
          price: "6.00",
          count: 4,
          description:
            "Valentine Gift By Shining Diva Italian Designer Non Precious Metal Jewellery Set for Women"
        }
      ]
    };
  }
  render() {
    return (
      <div class="row">
        {this.state.products.map(product => (
          <div class="col-lg-4 col-md-6 mb-4">
            <div class="card h-100">
              <img
                class="card-img-top"
                src={product.img}
                alt=""
                width="100px"
              />
              <div class="card-body">
                <h4 class="card-title">{product.name}</h4>
                <h5>${product.price}</h5>
                <p class="card-text">{product.description}</p>
              </div>
            </div>
          </div>
        ))}
      </div>
    );
  }
}

export default ShoppingApp;

Tested and verified to be functioning properly. No additional requirements needed for iteration. To see it in action, visit the following link here

Answer №2

When utilizing Webpack (assuming you kickstarted your project with CRA), a path such as ./images/ring.jpg is only accessible during the build process.

During runtime, use:

// product.img = "./images/heartstud.jpg";
<img class="card-img-top" src={require(product.img)} alt="" />

Alternatively, pre-import paths:

import heartstud from "./images/heartstud.jpg";

// webpack generates this in the build
console.log(heartstud); // /heartstud.84287d09.jpg

state = {
  products: [
    {
      img: heartstud,
    },
  ],
};

<img class="card-img-top" src={product.img} alt="" />

Refer to Adding Images in CRA.

Please note the typo: "'./images/heartstud.jpg'" (an additional ')

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

Attempting to alter the background image through the action of clicking on an image using jQuery, HTML, and CSS

I have created custom weather icons like a sun, cloud, and rainy cloud using Photoshop. My goal is to allow users to click on these icons and change the background image of the website's body. However, despite my efforts, clicking on the images does n ...

Is it possible to load JavaScript code once the entire page has finished loading?

My webpage includes a script loading an external JavaScript file and initiating an Ajax query. However, the browser seems to be waiting for example.com during the initial page load, indicating that this external dependency may be causing a delay. Is there ...

The paragraph text should dynamically update upon clicking a button based on JavaScript code, however, the text remains unchanged despite attempts to modify it

I recently started learning JavaScript and wanted to update the content of a paragraph when a button is clicked. However, I encountered an issue where this functionality doesn't seem to work. <body> <p id="paragraph">Change Text on cl ...

The code is malfunctioning on this site (yet functions perfectly on a different website)

So I have a question that may seem silly, but it's worth asking. I'm attempting to create a sticky div element that stays in place when you scroll past a certain point on the page. This is the script I have: <script type="text/javascript"> ...

Adjust the text size of a label in material-ui

Hey everyone, I'm struggling with something here. I need to adjust the font size of the label that goes along with my textfield. So far, I've only been able to change the font size of the input itself and not the label. Here's the code for ...

Enabling table row scrolling with keyboard navigation in React

Struggling to figure out how to make my table scroll while navigating through the rows using the onKeyDown event. It seems that the event isn't updating when using the keyboard, even though the highlighting of the selected row with selected is working ...

Using React with Typescript: What is the best way to implement useMemo for managing a checkbox value?

I am currently developing a to-do list project using React and Typescript. At the moment, I have successfully implemented the functionality to add new to-do items via a form and delete them individually. Each item includes a checkbox with a boolean value. ...

Utilizing various layouts in ASP.NET MVC with AngularJS

I am setting up two different layouts, one for visitors and one for management. Routes: app.config(['$routeProvider', function ( $routeProvider) { $routeProvider .when('/', { templateUrl: 'Home ...

Tips for loading a partial view page in a specific element using Angular JS after clicking a button

I'm facing an issue with my AngularJS partial view page not loading after a button click. I've set up the initial rendering page, but when we click the button, the partial view page doesn't render properly because the angular modules are not ...

How do you vertically span a grid element across 3 rows using Material UI?

This particular scenario may appear to be straightforward, but the official documentation of Material UI lacks a clear example on how to achieve this. Even after attempting to nest the grid elements, I encountered an issue where the grid element on the ri ...

`In AngularJS, the same URL ('/') can display different templates depending on the user's login status.`

What is the most effective way to configure routing and templates in AngularJS to display a distinct front end and login area for visitors, while presenting a dashboard to logged-in users all on the same base URL ('/')? These two pages have comp ...

Having troubles with delayed state changes due to setState being used within useEffect

I have been working on a slider effect using React Hooks and Redux, and here is the code I am using: const Barchart = ({chartData}) => { let newArray = [] let len = chartData.length const [XArray,setXArray]=useState([chartData]) const [ ...

Having trouble with parsing JSON data in Swift?

I've been attempting to utilize Swifty JSON for parsing a local file. While I am able to successfully store content in the data variable, I seem to be encountering issues when trying to use JSON from the SwiftJSON framework as it is not storing any co ...

Is it acceptable to replicate another individual's WordPress theme and website design in order to create my own WordPress website that looks identical to theirs?

It may sound shady, but a friend of mine boasts about the security of his WordPress website, claiming it's impossible to copy someone else's layout or theme. However, my limited experience in web development tells me otherwise. I believe it is po ...

Storing segments of URL data for future use in React applications

Is there a way to extract information from a URL? I wish to utilize the appended details in this URL http://localhost:3000/transaction?transactionId=72U8ALPE within a fetch API. My goal is to retrieve the value 72U8ALPE and store it either in a state var ...

dynamic jquery checkbox limit

I am working with the following HTML code: <input type="checkbox" id="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1 <input type="checkbox" id="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2 &l ...

What is the correct way to assign a $scope variable after a successful ajax call?

Currently, I am working with Symfony and AngularJs 1.6.8 along with Symfony 3.4. Below is the configuration setup that I have: base.html.twig <html lang="en" data-ng-app="CeocApp" ng-controller="CeocController"> //css for the app <link id="ng ...

I am looking to manage user-related data in the comment model using mongoose and express

I have a user, post, and comment modal This is my comment modal import mongoose from "mongoose"; const CommentSchema = new mongoose.Schema({ postId: { type: mongoose.Schema.Types.ObjectId, ref: "Post", }, userId: { t ...

Navigational bar with React and Next.js. Issue: Hydration unsuccessful due to inconsistencies between the initial UI and the server-rendered content

I am working on a project with Next.js and React. I've created a navbar component but I keep encountering the following error message multiple times: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warni ...

Exploring the capabilities of IBM Integration Bus in handling JSON parsing operations

Hello, I am currently facing an issue with parsing JSON data in the IIB Toolkit. The error message thrown by the java compute node is: "java.lang.NoClassDefFoundError: org.json.JSONObject" When attempting to parse incoming JSON messages using UTF-8 encodi ...