Effortlessly arranging images in a row with React

QUERY

I have a handful of PNG image files saved in the same folder as my React component and have successfully imported them. Now, I am looking for a best practice method to display all these images - let's assume there are 4 images - within their respective boxes as shown in the example picture below. I want them to be displayed side by side, accompanied by their name and price aligned below each image, similar to Craigslist's gallery view when viewing posts with images.

For instance:

<img src={Logo} alt=“website logo”/>

<img src={Mogo} alt=“website mogo”/>

<img src={Jogo} alt=“website jogo”/>

<img src={Gogo} alt=“website gogo”/>

Can I achieve this using

products.map((product, index, image?))...
?

SOURCE CODE

const Product = props => {
  const { product, children } = props;
  return (
    <div className="products">
      {product.name} ${product.price}
      {children}
    </div>
  );
};

function App() {
  const [products] = useState([
    { name: "Superman Poster", price: 10 },
    { name: "Spider Poster", price: 20 },
    { name: "Bat Poster", price: 30 }
  ]);

  const [cart, setCart] = useState([]);

  const addToCart = index => {
    setCart(cart.concat(products[index]));
  };

  const calculatePrice = () => {
    return cart.reduce((price, product) => price + product.price, 0);
  };

  return (
    <div className="App">
      <h2>Shopping cart example using React Hooks</h2>
      <hr />
      {products.map((product, index) => (
        <Product key={index} product={product}>
          <button onClick={() => addToCart(index)}>Add to cart</button>
        </Product>
      ))}
      YOUR CART TOTAL: ${calculatePrice()}
      {cart.map((product, index) => (
        <Product key={index} product={product}>
          {" "}
        </Product>
      ))}
    </div>
  );
}

https://i.sstatic.net/3OL1a.png

Answer №1

Enclose the list of products within a div tag (

<div className="productsContainer">
) and style it to display as a flex container with wrapping enabled.

Ensure the width of each product item (products) is set to 50% or less.

To display the image, include the <img> tag as one of the child elements or directly within the product object. Remember to update the data to include the src attribute for the image.

const { useState } = React;

const Product = ({ product, children }) => (
  <div className="products">
    {product.name} ${product.price}
    {children}
  </div>
);

function App() {
  const [products] = useState([
    { name: "Superman Poster", price: 10, logo: 'https://picsum.photos/150/150?1' },
    { name: "Spider Poster", price: 20, logo: 'https://picsum.photos/150/150?2' },
    { name: "Bat Poster", price: 30, logo: 'https://picsum.photos/150/150?3' }
  ]);

  const [cart, setCart] = useState([]);

  const addToCart = index => {
    setCart(cart.concat(products[index]));
  };

  const calculatePrice = () => {
    return cart.reduce((price, product) => price + product.price, 0);
  };

  return (
    <div className="App">
      <h2>Shopping cart example using React Hooks</h2>
      <hr />
      <div className="productsContainer">
        {products.map((product, index) => (
          <Product key={index} product={product}>           
            <img src={product.logo} alt="website logo" />
            
            <button onClick={() => addToCart(index)}>Add to cart</button>
          </Product>
        ))}

      YOUR CART TOTAL: ${calculatePrice()}
      {cart.map((product, index) => (
        <Product key={index} product={product}>
          {" "}
        </Product>
      ))}
    </div>
  );
}

ReactDOM.render(
  <App />,
  root
);
* {
  box-sizing: border-box;
}

.productsContainer {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.products {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 45%;
  margin: 0 0 1em 0;
  padding: 1em;
  border: 1px solid black;
}

.products img {
  margin: 0.5em 0;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

Answer №2

The optimal method for showcasing them next to each other is to utilize CSS classes flex-row for a horizontal layout and flex-column for a vertical arrangement within the primary div element.

Answer №3

const Item = props => {
  const { item, children, img } = props;
  return (
    <div className="items">
      {item.name} ${item.price} ${img}
      {children}
    </div>
  );
};

items.forEach((item, index, image?))...?

Could this approach work instead?

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

Add some animation to elements when the page loads

I am curious about triggering a css animation when the page loads. I am currently experimenting with css animations for the first time. Here is what I have created so far: https://jsfiddle.net/7prg793g. However, it only works upon hover at the moment. * ...

Deleting an element in an Array of objects using Typescript

export class AppComponent implements OnInit { title = 'bucketList'; bucketList: BucketListItem[] = [ new BucketListItem( "Goa Trip", "Travel to Goa" ) ]; ngOnInit() { } onItemAdded(eventData) ...

A guide on utilizing Redux to schedule actions with a timer

In order to update the display of a stateless component every second, I have been trying different approaches. One of my initial methods involved using window.setInterval within the render function. However, this resulted in a new timer being created each ...

jQuery mobile menu: Scroll to content after closing the menu

I am currently working on a project where I am using mmenu for the first time. It's functioning as expected, but there is one particular issue that I would really like to have resolved. Here is the URL: What I am hoping to achieve is that when a men ...

In terms of professional design, which is the better choice - Bootstrap or Foundation?

Greetings! I am in the process of creating a website with a professional design. I'm trying to decide between using Bootstrap 3 or Foundation 5 for my CSS framework. Which one do you recommend for designing purposes? Is there another CSS framework t ...

Creating an input field within a PixiJS Canvas: Enhancing PixiJS UI with typed-signals for seamless import/export interactions

I am trying to utilize PixiJS UI version 2.1.2 to add an input field to a canvas rendered by PixiJS version 8.2.0. The PixiJS part works fine, but I'm encountering issues with importing @pixi/ui. Firefox displays: "Uncaught SyntaxError: ambiguous ind ...

HTML - Customizing container with background color and ensuring minimum height of 100%

After creating a dynamic page using Bootstrap, I managed to add a sticky nav bar and footer. The navbar, footer, and page content are all in black color. I want the main content area to be white with black sides matching the background. Currently, I ca ...

Can multiple objects be grouped together and easily dragged in Leaflet?

Is there a way to group a set of objects together so they can be dragged simultaneously? I want to make multiple objects draggable on a map and have them behave as a single marker when moved. Currently, I have a geojson file containing several objects that ...

Error: Swagger-codegen encountered an issue where 'Object' arguments were disregarded

I've encountered a strange error that I can't seem to troubleshoot through online searches. My current project involves converting swagger files to typescript using a script. The error message simply states what's in the title, and unfortuna ...

Measuring the space between HTML input elements

Can anyone help me with spacing out two input fields on my form? Here is what it looks like currently: https://i.sstatic.net/KRZ58.png. This is the code I am using: <form class="popup-form" id="login-popup-form"> <label>Your username/email:< ...

Tips on utilizing bootstrap alongside html GET request for retrieving input values?

I created an HTML code using the bootstrap library. Essentially, I need someone to visit my website, input their information, and have their inputs stored for internal analysis. After the user enters their input, the URL will redirect to a 'search&apo ...

The backbone module is experiencing formatting issues

I'm new to learning backbone.js. I've created the example below, but unfortunately, it's not functioning properly. Can someone please help me understand why? The goal is to simply display the name within my div element. (function($) { ...

Do we need to employ strict mode when utilizing specific ES6 functions in Node.js?

There has been a debate circulating at my workplace regarding whether or not it is necessary to include 'use strict' when using ES6 in Node.js without Babel. Some argue that certain ES6 methods may not function correctly without it, but I haven&a ...

The unzipper will disregard any empty directories within the file

I am a Japanese Web Developer. Unfortunately, I struggle with English. https://www.npmjs.com/package/unzipper This library is currently in use by me. Below you will find my code snippet: // unzip module import fs from 'fs-extra' import unzip ...

Eliminate inner margin from the canvas of a bar chart created with ChartJS

I am looking to use Chart.js to create a single stacked bar chart that visualizes progress towards a specific financial goal. I have added a dotted line on top of the chart to represent this goal amount. The issue I am facing is that there is unwanted pad ...

Commence {{@index}} at 1 instead of 0 in Handlebars, without any template specified

Currently, I am utilizing the @each loop to go through items but would like to start with an index of 1 instead of 0. I attempted to resolve this by including the following code snippet: var Handlebars = require('handlebars'); Handlebars.regist ...

Trouble linking CSS file with Plotly Dash interface

Transitioning from plotly to dash, I am looking to incorporate a css file to enhance the appearance of my dashboard. The structure consists of app.py and index.py in the main directory, with an additional style.css file located in the /assets folder. Desp ...

What is the method for stretching the navbar and content to fill the entire viewport in Bootstrap?

Can anyone help me with an issue regarding a navigation bar and content created in Bootstrap 5? I'm trying to use vh-100 to make both the navigation bar and content stay on the view page without a scrollbar. However, the size of the navigation bar is ...

Tips for modifying only one property after receiving an object from an HTTP GET request

Within my Angular application, I have defined an object structure like this: export class Article { id: number; author: number; title: string; content: string; date: Moment; readingTime: number; draft: boolean; constructor(obj: Partial< ...

Navigating the Complexities of Ajax POST and Stringify

As I delve into the world of POST with Ajax, one common trend I've noticed is the use of stringify on static arrays in many examples. In my specific case, I am constructing an array using jQuery objects extracted from <input> values. The Power ...