Generate an adjustable grid layout (with rows and columns) to display information retrieved from an API request

I have recently started learning React JS and JavaScript. To practice, I am working on a small project where I am facing an issue with creating dynamic rows and columns. My aim is to display data in 4 columns initially and then move to a new row and column for the 5th set of data, continuing this pattern until all the data is displayed.

For reference, you can view the layout here.

Below is the code snippet:

import React, { Component } from 'react';
import './itemslist.css';
import axios from 'axios';
import { Link } from 'react-router-dom';

class ItemsList extends Component{

  constructor(props){
    super(props);
    this.state = {
      productList: []
    }
  }

  async componentDidMount(){
    const homeAPI = `${window.apiHost}/api/items/`;
    await axios.get(homeAPI).then(res => {
      this.setState({productList: res.data.result.product_data})
    })
  }


  render(){

    // struggling to implement the row and column logic here.

    const products = this.state.productList.map((product, i)=>{
      return(
          <div className="card text-center card_style" key={i} style={{marginBottom: '120px'}}>
            <div className="card-header">
              {product.name}
            </div>
            <Link to={`/items/${product.id}`}>
              <img className="card-img-top card_image" src={product.image} alt="Card"/>
            </Link>
            <div className="card-footer text-muted">
              <p className="card-text">{product.description}</p>
              {product.price}
            </div>
          </div>
      )
    })

    return(
      <div className="item_list_main">
        {products}
      </div>
    )
  }
}

export default ItemsList;

Any suggestions on how I can address this challenge?

Answer №1

Include the following code snippet in your CSS stylesheet.

If you need more information, check out this link

.item_list_main {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}

This configuration sets up a grid layout where each row contains four equal-width columns.

Answer №2

@Milan_Thapa. It is possible to utilize width: 25%; for each component, however, keep in mind that the sizes of components may vary greatly in terms of both width and height.

To address this issue, an effective solution is to implement Masonry, a popular choice for handling varying component sizes.

I trust this suggestion will be helpful for you.

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 guide on sending multiple input values using the same class name or id through ajax

My goal is to send multiple input values through AJAX to my PHP script. Everything works smoothly when I use getElementById. However, I have the functionality to add a child. The issue arises when it only retrieves values from the first child while iterati ...

What is the functionality of an Angular service that retrieves an

It appears that Angularjs services are constructed by passing in a Contructor function: app.service('serviceName', function(){ this.var1 = 'foo'; this.method1 = function(){ } }); Angular executes this function using the new ...

Guide to setting dynamic text in the defaultValue attribute using the TextField component from Material-UI

When the edit value is true, I want to include Edited text after the message. How can I achieve this using the TextField component from MUI? import React, { useState } from "react"; import Box from "@mui/material/Box"; import TextField ...

Determine if Param is empty or not within the context of express.js

I am looking to create a table and populate it with all the parameters that are not empty in the parameter list provided below: http://localhost:5002/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="407535732b7008121931190539142 ...

I am integrating Material-UI's flat pagination feature into my React project

Looking for advice on implementing pagination logic in my application. I am fetching a list of jobs from the freelancer api and using https://www.npmjs.com/package/material-ui-flat-pagination to handle pagination. The page numbers are displaying correctly ...

Utilize modules within the AppModule to promote modularization and maintain separation of concerns in Angular 2

When using templates like those from the ASP.NET Core JavaScript services, typically a single module named AppModule is included. However, in my application, which is divided into two logical areas (AreaA and AreaB), I thought it would be better to use two ...

Having trouble showing the text on the screen, but after checking my console, I notice empty divs with p tags. Surprisingly, the app is still functioning properly without any

Currently, I am developing a joke app entirely on my own without any tutorials. One of the components in the app is SportsJokesApi, which retrieves data from a local json folder (SportsJokesData) that I have created. Here is how it is structured: const Sp ...

Java Entity Framework Indexing Tables

I am currently utilizing ASP.Net Core and have implemented EntityFramework to create a controller with views. Specifically, I am in the process of enhancing the Index view to make it dynamic with dropdown selections. I have successfully completed everythin ...

A guide to eliminating the # symbol from the localhost link in a React JS application

Whenever I create or update something on my page, the link from e.g. http:localhost:3000/#/adduser becomes http:localhost:3000/?first_name=asdqwe&last_name=asdqwe&email=asdqwe%40gmail.com&gender=Male&password=asdqwe#/adduser. This is unexpe ...

Having trouble with npm debounce in ReactJS?

When using the npm debounce package in ReactJS, I encountered an error with the code below: Javascript - Uncaught TypeError: Object(...) is not a function The error occurs when passing the function into the debounce() method. import React, { Component ...

How to programmatically disable a button using React and Material-UI: A step-by

Attempting to deactivate a button once the user has clicked on it, but from a handler function. I have come across these two related questions: React Material UI: How to give a button a custom color when disabled? Change disable attribute in react select ...

AngularJS: Organizing Controllers Horizontally Within ngRepeat

My data consists of a table with 100 rows, each representing a complex object that is an instance of a specific type. User interactions trigger operations on these objects individually, with each row having unique operations independent of the others. $sc ...

Having trouble with the visibility of label text in Material UI TextField? Let's figure out why the label text

I recently started learning ReactJs and material-ui, but I've encountered a problem with the material TextField. Below is the code snippet that generates the issue: https://i.sstatic.net/FpAtV.png The problem lies in the fact that the label="T ...

Using the Google Identity Services JavaScript SDK in conjunction with Vue and TypeScript: A comprehensive guide

I am currently working on authorizing Google APIs using the new Google Identity Services JavaScript SDK in my Vue / Quasar / TypeScript application. Following the guidelines provided here, I have included the Google 3P Authorization JavaScript Library in ...

The issue of the loadeddata event not firing on a Next.js project with the <audio> element

I can't seem to understand why the loadeddata/loadedmetadata event is not consistently firing in my application. It seems like there might be a race condition causing this issue, but I've tried many different things and I'm stuck. Basically ...

Enhancing readability in a vertical CSS menu with proper spacing

I'm looking to increase the spacing between each menu item as they appear too close together. Can someone help me with managing this? The menu names are currently right under one another, almost touching. What is the best way to create more space betw ...

Error: Unable to convert value "undefined" to ObjectId (string) at reference " _id" for object "Product"

I'm encountering an error as a newcomer to node and react. CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Product" at model.Query.exec (D:\Amazon Clone MERN\node_modules\mongoose\li ...

Easily validate your email with this straightforward form. Completely puzzled

Today's challenge is tackling the email validation form issue. While searching for a solution, I stumbled upon an interesting code snippet: http://jsfiddle.net/jquery4u/5rPmV/ dyingOverHere(); The code seems to work flawlessly in the demo provided. ...

How can the parent div's height be determined by the child div when using position: absolute?

I am struggling with setting the height of a parent div that contains a nested child div with absolute positioning. The child div has a fixed height of 652px, but I cannot seem to get the parent div to match this height. I have tried adjusting the clear an ...

Issue with organizing columns in Plotly-Dash using personalized CSS

I expected the code below to create three adjacent drop-down menus under a tab labeled Setup, but I'm actually seeing them stacked on top of each other. What mistake am I making? Any guidance would be highly appreciated! I've provided the releva ...