What is the process for implementing a grid with 5 columns on larger screens and 2 columns on smaller screens using reactjs?

I am currently working on building a Grid using material UI and reactJs.

I found the guidelines on this link https://mui.com/system/react-grid/.

However, there seems to be an issue with creating 5 columns in the grid. I attempted to create a custom grid structure featuring 5 columns for large screens, 3 columns for medium screens, and 2 columns for mobile devices.

While I managed to achieve the 5-column layout, I encountered difficulties trying to implement a 2-column layout for mobile devices.

Current display:

1 2
3 4
5
11 22
33 44  

Expected output:

1  2
3  4
5  11
22 33
44

My code can be viewed at: https://codesandbox.io/s/nostalgic-joliot-3xc7bo?file=/src/App.tsx

import * as React from "react";
import {
  /* components utilized */
  Typography
} from "@mui/material";
import { styled } from "@mui/material";

export const DGrid = styled("div")({
  display: "flex",
  alignItems: "flexStart",
  flexWrap: "wrap"
});

export const DGridCol = styled("div")({
  width: "calc(100% / 5 - 16px)",
  marginBottom: "24px",
  marginRight: "20px",
  "&:last-child": { marginRight: "0px" },
  "@media (max-width: 768px)": {
    width: "calc(100% / 2 - 8px)",
    marginBottom: "15px",
    marginRight: "16px",
    "&:last-child": { marginRight: 16 },
    "&:nth-child(2),&:nth-child(4),&:nth-child(6)": { marginRight: 0 }
  }
});

/**
 * Implementation of the components
 */
export default function App() {
  return (
    <div>
      <DGrid>
        <DGridCol>
          <div style={{ background: "red" }}>1</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>2</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "red" }}>3</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>4</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "red" }}>5</div>
        </DGridCol>
      </DGrid>

      <DGrid>
        <DGridCol>
          <div style={{ background: "red" }}>11</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>22</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "red" }}>33</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>44</div>
        </DGridCol>
      </DGrid>
    </div>
  );
}

Looking forward to any suggestions.

Answer №1

To start off, it's important to group all elements within a single container called DGrid since each grid is meant to be displayed in blocks.

   <DGrid>
        <DGridCol>
          <div style={{ background: "red" }}>1</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>2</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "red" }}>3</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>4</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "red" }}>5</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "red" }}>11</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>22</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "red" }}>33</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>44</div>
        </DGridCol>
      </DGrid>

Next, adjust the CSS property to ensure that every even item has no right margin when nested inside a DGridCol. This way, pairs of items will have no space between them and align properly with the previous column.

export const DGridCol = styled("div")({
  …
  "@media (max-width: 768px)": {
    …
    "&:nth-child(n+1)": { marginRight: 0 }
    …

Answer №2

For a grid layout, consider using the actual grid layout CSS property instead of display: "flex". Switch to display: "grid" and specify the columns you want to include. It's recommended to follow a "mobile first" design approach. This involves setting up the CSS for the mobile view first and then using media queries to adjust the CSS rules for larger screen sizes.

Here is an example:

export const DGrid = styled("div")({
  display: "grid",
  columnGap: "20px",
  rowGap: "24px",
  gridTemplateColumns: "repeat(2, 1fr)",   // 2 column mobile
  "@media (min-width: 768px)": {
    gridTemplateColumns: "repeat(3, 1fr)", // 3 column "medium"
  },
  "@media (min-width: 1280px)": {
    gridTemplateColumns: "repeat(5, 1fr)", // 5 column "large"
  },
});

export const DGridCol = styled("div")({});

* Note: Adjust the breakpoint values according to your application's requirements.

Full code can be found in the link below

https://i.sstatic.net/5lN4k.png https://i.sstatic.net/dlQWB.png https://i.sstatic.net/7OtXB.png

https://codesandbox.io/s/sharp-buck-xuqok0?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.tsx&theme=dark

Example usage of the components:

// Example component usage
<DGrid>
  <DGridCol>
    <div style={{ background: "red" }}>1</div>
  </DGridCol>
  <DGridCol>
    <div style={{ background: "yellow" }}>2</div>
  </DGridCol>
  <DGridCol>
    <div style={{ background: "red" }}>3</div>
  </DGridCol>
  ...
</DGrid>

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

Which specific file name patterns does npm publish consistently exclude?

When using the npm publish command, the documentation mentions that certain files will not be included in the package unless explicitly added to the "files" list in package.json or un-ignored with a specific rule. What exactly are these "certain patterns"? ...

checkbox remains stuck at the same value

The checkbox value is not changing to true or false, it appears to be stuck on true. Even if a user does not wish to agree to the terms, it still shows as if the user has not unchecked the checkbox (although the tick mark is removed). I am trying to figu ...

Immediately Invoked Function Expression in Javascript

const user = { name: "John", age: 30, lastName: "Smith" } (({name, lastName}) => { console.log(name); console.log(lastName); })(user); An error occurred: {(intermediate value)(intermediate value)(intermediate value)} is not function ...

JSDOM failing to retrieve complete list of elements from webpage

I'm currently struggling with a simple webscraper using JSDOM. Here's the code snippet I've been working on: const axios = require("axios"); const jsdom = require("jsdom"); const { JSDOM } = jsdom; let v = "15" ...

Downloading xml data in an Angular table is a straightforward process that can be achieved

I have a table displaying a list of data. Each row includes an option to download XML data. 0{ firstName: null id: "04674" lastName: null orderId: "TEM001" productId: "TEM" receiptPeriod: "2016-02-26" ...

Guide to adding content and icons to the top navbar on the right side using vue.js

In the process of developing a fixed top navbar, I encountered an issue while trying to add right side icons and additional content. The goal is to include two icons, as shown in this example: example link, along with profile and cart information on the ri ...

Detecting the presence of a mobile keyboard on a website: strategies and techniques

After implementing the code below, I noticed that nothing happens when the keyboard is visible. Despite my efforts to troubleshoot, it seems that window.screen.height remains unchanged. class TestPage extends React.Component { constructor(props) { ...

When the browser window is resized to mobile view, a div is overlapped by an image

I've encountered an issue with the image size and position when resizing to mobile view in the browser. .extension { display: table; padding: 50px 0px 50px; width: 100%; height: auto; color: #fff; background-color: #558C89; ...

How can one efficiently navigate through extensive functions without risking surpassing the stack limit?

I am currently developing an application in Node.js that requires numerous configuration and database calls to process user data. The problem I am facing is that after reaching 11,800+ function calls, Node throws a RangeError and exits the process. The er ...

Updating the route path for version control in Express.js

When working with an ExpressJS application, the following paths should be considered: GET /v1/users/detail GET /v2/users/detail The corresponding routers are as follows: // v1/users.js router.get('/v1/users/detail', (req, res, next) => res. ...

Please type the file name into the provided text box

Is there a way to automatically insert the filename of an uploaded file into an existing text input using either or valums.com/ajax-upload/? (I am working with php) For example, in a textbox: <input name="image" type="text" value="file_name" /> ...

Vue component doesn't update reactively until the template value changes

I have a child component in my Vue application that utilizes Vuex for managing certain values. Currently, when I trigger an action in the parent component, it should also trigger the child component. This is achieved by passing an active boolean prop to t ...

Troubleshooting problem with Ajax Calendar Extender

I have a text box where I need to save the chosen date from a calendar. To achieve this, I am using an AJAX calendar extender and setting the target control property to the textbox ID. However, when I click on a button on the same page, I lose the selected ...

Changes in a deep copy of an object in a child component are directly reflected in the parent object in VueJS

Let's begin by discussing the layout. I have a page dedicated to showcasing information about a specific company, with a component Classification.vue. This component displays categories of labels and the actual labels assigned to the current company. ...

Tabulator automatically inserted 'numrow' after retrieving the data

I have a table of undetermined information (consisting of various columns and rows). I am now at the point where I need to utilize the function table.updateData(), but this function specifically requires the column id to be present in the data structure. S ...

Having trouble parsing asynchronous script with cheerio parser

Utilizing cheerio for web crawling poses a challenge when encountering websites with asynchronous scripts. When attempting to extract all the scripts from such websites, they are often missed in the process. Here is an example of the code I am currently us ...

I need help with a process to extract information from a database and convert it into an object specifically for my situation

Currently, I am utilizing the postgres row_to_json function to retrieve data that has been stored using JSON.stringify(). However, upon retrieval and attempting to parse it with JSON.parse(), an error message stating "unexpected token ," is returned. The ...

Customize your select element's background using jQuery when the content changes

Here is a select element with different options to choose from: <select class="state"> <option value="1">Done</option> <option value="2">Closed</option> <option value="2">Open</option> <option v ...

Hidden IFrame for Jquery File Upload

I was looking for a quick guide on setting up an AJAX-style file upload using a hidden iframe. Below is the section of HTML code related to the form: <div id = "file" class = "info"> <form id="file_upload_form" method="post" enctype=" ...

Find the perfect match with Material UI Autocomplete's feature that allows you to search from the start of

Implementing material UI Autocomplete field in my React project, I aim to restrict search functionality to only match keywords from the beginning (for certain fields of the objects): Here's an example scenario with the available options: [ {data1: ...