Creating various rows within a loop can be achieved by using conditional statements to determine

I am faced with a challenge of handling an array of images, among other properties, and I aim to achieve the following outcome:

https://i.sstatic.net/BYajY.png

As the images reach the end of the container (which fits 4 images on desktops and adjusts for smaller screens), a new div should be created to contain the overflow.

If I were working with static data, my approach would look something like this:

<div>
   <div className="d-flex products-container justify-content-between mt-5">
      <div className="border">
         <img src={require('../../assets/images/Products/molde.png')} alt="Product" />
      </div>
      <div className="border">
         <img src={require('../../assets/images/Products/molde.png')} alt="Product" />
      </div>
      <div className="border">
         <img src={require('../../assets/images/Products/molde.png')} alt="Product" />
      </div>
      <div className="border">
         <img src={require('../../assets/images/Products/molde.png')} alt="Product" />
      </div>
   </div>
   <div className="d-flex products-container justify-content-between mt-5">
      <div className="border">
         <img src={require('../../assets/images/Products/molde.png')} alt="Product" />
      </div>
      <div className="border">
         <img src={require('../../assets/images/Products/molde.png')} alt="Product" />
      </div>
      <div className="border">
         <img src={require('../../assets/images/Products/molde.png')} alt="Product" />
      </div>
      <div className="border">
         <img src={require('../../assets/images/Products/molde.png')} alt="Product" />
      </div>
   </div>
</div>

However, since the data is fetched dynamically from an API and generated through a loop, the result differs:

props.products.map(product => {
   return <div className="border">
             <img src={product.img} alt="Product" />
          </div>
})

Due to this dynamic nature, I encounter the following output:

https://i.sstatic.net/N9vKN.png

I have experimented with using conditional statements and the index value to control the behavior, but haven't been successful. Any suggestions on how to solve this issue?

Answer №1

Bootstrap offers a convenient way to create columns using its grid classes.

By adding col-xs-6 col-sm-3, you can achieve 2 columns on mobile and 4 columns on larger screens.

No need to worry about separating them into rows - the CSS takes care of that automatically.

For more information, check out https://getbootstrap.com/docs/4.5/layout/grid/

Answer №2

To handle this situation in a more sophisticated manner, utilizing the index variable appears to be a feasible solution. Consider implementing a snippet similar to the following:

props.products.map((product, index) => {
   if (index + 1 % 4 === 0) { // checking if index plus one is divisible by 4
       return <div className="border">
             <img src={product.img} alt="Product" />
          </div>
       }
       <div className="d-flex products-container justify-content-between mt-5">
    } else {
       return <div className="border">
             <img src={product.img} alt="Product" />
          </div>
    }
})

Answer №3

Consider changing one of your CSS class attributes to

style="display:inline-block"
.

You could experiment with adding inline CSS to each block using: style="display:block".

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

Changing the arrow in jQuery's slideToggle for different div elements is a breeze

Good day, I'm struggling with getting the arrow switch to work correctly for slideToggle. Even though I have three of them, the arrow changes only for the first one - no matter which div I click on. Any suggestions on what I might be missing? Thank yo ...

Slideshow Display Suddenly Halts at the Last Image

I am currently working on a Bootstrap JS Carousel that showcases several images stored in the project folder. Each image's filepath is retrieved from an SQL Server database and displayed within the carousel. While the images are displaying correctly ...

What could be the reason for encountering the 'SyntaxError: Cannot use import statement outside a module' when trying to utilize the cloudinary module?

I am facing an issue while trying to utilize the Cloudinary module for resizing an image. Below is the code snippet I have: import cloudinary from 'cloudinary'; var cl = new cloudinary.Cloudinary({ cloud_name: "username", secure: true } ...

Steps for repairing a button positioned at the top of a nested container within a form

My search form includes side filters to help users narrow down their search, with the results appearing on the right. This is just a basic example, as my actual setup involves more filters. However, there is one issue – users have to scroll down the pag ...

`Vue JS table with Boostrap styling showcasing a loading indicator for busy state`

Issue: I need to show a loading icon while waiting for the table to load. https://i.sstatic.net/kRCbL.png I am utilizing Boostrap-vue JS, which is built on top of Bootstrap, and VueJS's "b-table" component to display approximately 3000 rows in a tabl ...

Error in React Toaster preventing redirect with useHistory() before reaching another page

When I try to display a message using react toaster and then redirect to another page using history.push('/'), the toaster fails to work properly. Instead, the page immediately redirects to the homepage without displaying the toast message first. ...

"Jquery's .append function may sometimes display as undefined when

$("#clckjson").click(function() { $(document).ready(function() { $.getJSON("fuelj.json", function(data) { $(data).each(function(i, item) { console.log(item.stationID); var $table = $('<table>'); $table.a ...

A streamline method for creating nested tables using Jquery

I've developed the following code snippet that generates a table within another table based on JSON response data. Code for Main Table var user = '<table width="98%" cellspacing="0" cellpadding="1" style="text-align: left; margin: 0 auto;&a ...

Symbol positioned beside the text in a react-select multiple label

Currently utilizing the react-select library, I am attempting to display icons next to the text of each label that can be added or removed using multiSelect. const data = [ { label: <svg /> && 'keyword one', value: 'keyword o ...

How come the hasOwnProperty function does not remove objects of type {}?

I am working with a complex type called ReactNode from the version @types/react 16.9.17 and TypeScript v3.7.4. import React, { ReactNode } from 'react'; My goal is to reduce this type to a new type that includes the property children. To achie ...

Increase the size of the SVG area

I'm still learning how to work with SVGs, so I appreciate your patience as I ask what may seem like a simple question. Currently, I have an SVG image that resembles a cake shape. See it here: https://i.sstatic.net/tDhUL.png Take a look at the code: ...

Is there a way to pass a c struct pointer into javascript using ffi?

I need help passing a pointer to a struct to a method in nodejs using ffi. I am encountering an error where the type of the JavaScript struct I created cannot be determined. How can I resolve this issue? Previously, I was able to successfully implement si ...

Having trouble displaying API JSON data in a Vue.js table component

In my HTML file, I have implemented fetching data from an API and displaying it in a table successfully. Now, I am trying to convert the HTML file to use Vue.js, but encountering some issues. Despite being able to fetch data from the API with Vue, the tab ...

Communication between the register service worker and the client page begins with the dispatch of a

Looking to pass a boolean variable to app.js when the registration onupdatefound function is triggered. This way, whenever a new update is received, app.js will be notified and I can display a popup with a refresh button. I have most of it implemented alr ...

Erase jQuery from the text

I am struggling with splitting or removing text from a filename. For example, if I have filenames like: 200726100_50-0002.JPG 230514008_60-0001.JPG The desired result should be: 230514008_60.JPG 200726100_50.JPG Am I not using the split function cor ...

React - updating state does not cause changes to elements rendered from variables

Currently, I am facing an issue where I have stored a component in a variable called const span = <span>{this.state.text}</span>. However, when I render this element and update the text within the state, the element fails to re-render. Below i ...

Avoid allowing image uploads that are too large in size

Is there a way to block an image from being uploaded if it exceeds a specified size limit? Currently, I am using angular-base64-upload and although my error message appears when the image is too large, the image still gets uploaded. I'm puzzled as to ...

setting the width of <input> fields to automatically adjust

Curious about CSS. I was under the impression that setting width:auto for a display:block element would make it 'fill available space'. However, when applied to an <input> element, this doesn't seem to hold true. For instance: <b ...

What causes the failure of hot reloading in the ReactJS Visual Studio 2019 template?

I have been experimenting with ReactJS on my personal and work computers. On my personal computer, I am using Visual Studio 2019, NodeJS 10.16.2, NPM 6.9.0, and webpack 3.11.0. Initially, hot reloading was functioning correctly when I started my project. ...

CSS - Tips for preventing elements from wrapping onto multiple lines

I am facing an issue with spans displayed inline in my browser. The text within my spans is being cut off when it reaches the right border of the browser, with half on one line and half on the next. I want to prevent this from happening by having the conte ...