Building a Flexible Grid Layout with React Material-UI: A Step-by-Step Guide on Using the Grid Component

My project utilizes React and MUI as the UI library. I have a substantial amount of elements that need to be organized in a specific manner. While the Grid component is typically effective for this purpose, I encountered some challenges.

 <Grid container
                direction="row"
                justifyContent="start"
                alignItems="center"
                spacing={4}
                className={classes.Grid}
            >
                {Cards.map(c => (
                    <Grid item xs key={c._id} >
                        <Card id={c._id} title={c.title} description={c.description} />
                    </Grid>
                ))}
</Grid>

Applying specific styles:

const useStyles = makeStyles({
    Grid: {
        margin: "auto!important",
        width: "90vw!important",
    }
});

Each element within the grid is set to have a distinct height and width. The current implementation yields the following result:

 _ _ _   _ _ _   _ _ _   _ _ _   _ _ _   _ _ _   _ _ _
|     | |     | |     | |     | |     | |     | |     |
|     | |     | |     | |     | |     | |     | |     |
|_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _|

         _ _ _           _ _ _          _ _ _  
        |     |         |     |        |     | 
        |     |         |     |        |     | 
        |_ _ _|         |_ _ _|        |_ _ _| 

Furthermore, the gap between elements is not consistently spaced and is affected by screen size. A wider screen leads to larger gaps between elements. My objective is to achieve the following layout:

 _ _ _   _ _ _   _ _ _   _ _ _   _ _ _   _ _ _   _ _ _
|     | |     | |     | |     | |     | |     | |     |
|     | |     | |     | |     | |     | |     | |     |
|_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _|

 _ _ _   _ _ _   _ _ _   
|     | |     | |     | 
|     | |     | |     | 
|_ _ _| |_ _ _| |_ _ _| 

My approach using css flex-box allowed me to achieve a closer representation of my ideal layout:

<Box
        sx={{
               display: "flex",
               justifyContent: "center" ,
               gap: "20px",
               flexWrap: "wrap",
               margin: "auto",
               width: "90vw",
           }}
       >
                {Cards.map(c => (
     <Card key={c._id} id={c._id} title={c.title} description={c.description}/>
                ))}
</Box>

In cases where the screen size is too small, items in the last row are wrapped onto a new row. The issue I encounter is that the columns on the last row are centered instead of being positioned at the start of the row, as I desire. The gap size remains consistent.

How can I achieve the desired positioning for the last row?

Answer №1

CSS

display: "grid",
gridTemplateColumns: "repeat(auto-fill, 220px)", //specifying the width of the card 
justifyContent: "center",
gridGap: "20px",

Body

<Box className={classes.List}> //applying CSS classes
    {Cards.map(c => (
        <Grid item xs key={c._id} >
            <Card id={c._id} title={c.title} description={c.description} />
        </Grid>
    ))}
</Box>

Answer №2

  1. To utilize the grid system, input the appropriate value in the breakpoints like sx, md, etc. Additionally, you do not have to include the props: direction, justifyContent, and alignItems in the Grid container.
<Grid item xs={3} md={3} key={c._id}>
...
</Grid>

For example:

<Grid container spacing={4}>
   {Cards.map((c) => (
     <Grid item xs={3} md={4} key={c._id}>
         ...
     </Grid>
   ))}
</Grid>

  1. When using FlexBox: simply remove the justifyContent='center' props.

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

What is the best way to ensure grid element takes up 100% of the available height within a flex column

I am working with this HTML structure: https://i.stack.imgur.com/fy5Yz.png My goal is to have the .SceneWithHistory-Container take up 100% of the available height in its parent element. Below is my CSS code: .Module-Container margin-top: 120px; displ ...

Error: Could not locate an element containing the specified text: /discover react/i

✕ issue with rendering learn react link (36 ms) ● unable to render learn react link TestingLibraryElementError: The element containing the text /learn react/i could not be found. This may be due to the text being split up across multiple elements. Con ...

The file or directory does not exist: 'G:Aframara Websiteimages' - ENOENT

Currently, I'm in the process of cleaning up the unused CSS in my website's style.css and bootstrap.min.css files during development. I am utilizing PostCSS and Parcel for this task. After installing PostCSS and Parcel, I proceeded to create a p ...

Arrow icon from Material UI for a smaller device

As I work on coding a tab bar, I have encountered an issue where the indicator arrow button () is not displaying when the width of the tab bar goes below 600px. I would like it to appear like this: https://i.stack.imgur.com/PDum9.png However, currently i ...

Spacing the keyboard and input field in React Native

Is there a way to add margin between the input and keyboard so that the bottom border is visible? Also, how can I change the color of the blinking cursor in the input field? This is incorrect https://i.sstatic.net/Jsbqi.jpg The keyboard is hidden https: ...

Updating TextField Values with React Material UI

At the beginning of each session, I initialize the state with these variables: state = { firm: null, office: null, salesCode: null, account: null } Each TextField in my application is rendered like this: <TableCell> <TextFie ...

Troubleshooting Ineffective Node MySQL Connection

I'm a beginner in Node and Express, and I have this code that's supposed to connect to a MySQL database. However, when I try to access 127.0.0.1:9080, nothing seems to happen. I've checked the console for errors, tried it on multiple browser ...

Establishing a distinct registry for a particular package within the .npmrc configuration file

Today, I encountered a new challenge that I've never faced before. I am currently in need of having private node packages published in both a private and public repository under the same @scope. The packages on npmjs.org are stable and open to the pu ...

generate dynamic custom headers in an express application for accessibility by an Angular application

https://i.stack.imgur.com/6jyNE.pngRecently, I have started using Express and despite my extensive research, I haven't been able to find a solution to my issue. The problem is that I am receiving headers in my Express app, but when I attempt to make t ...

Developing a React component npm package using webpack or babel is proving to be unsuccessful

I am encountering an issue while creating a React Component npm package. Within a component of this package, I am utilizing an image (import MyPicture from 'path/image.png'). My intention was to export it as a git npm package, so I decided to use ...

Show various Bootstrap Alert Messages based on the type of error detected?

Trying to figure out how best to explain this, here it goes! I am working on a website and I want to incorporate alert messages. Check out some examples here. Depending on the form inputs, I need different alerts to be displayed. PHP will validate the in ...

Moving a popup div along with a marker in Leaflet can be achieved by using the set

After creating a map using leaflet and adding markers to different locations, I implemented code that displays a popup div with a message when a marker is clicked. Here is the code snippet: markers.on("click", function(d) { div.html("This is Some info ...

Please be patient and allow the function to complete before moving forward

Currently, I am in the process of building my first nodejs/DynamoDB application and it involves working with JavaScript for the first time. My goal is to save a new record after scanning the table and using the results of the scan as a basis. After doing s ...

Using background-image in Internet Explorer has always been a challenge

HTML <div id="banner" style="display: block; background-image: url('images/swirl_home.gif'); background-repeat: no-repeat; background-color: #e7e7e7;"> <div id="Hi"> some text here... </div> & ...

Setting up environments utilizing restify

Having experience with gulp, I am well-versed in setting up a distinct configuration for each environment within a single configuration file. This allows for running gulp dev to initiate the server using the development environment configuration, gulp stag ...

Creating a custom input mask with dynamic value in reactIs this rewritten text okay?

Programming Tools : Developed using JavaScript with React, React Hook Form, and Material UI Objective : To implement an input field with a custom mask that includes static values, variable values, and user-defined values. Below is where the "Name" field ...

Is there a way to avoid getting a 404 error in Express when using multiple static directories?

I am working on serving files from two different folders to keep my admin and client content separate. The code I have set up initiates the two folders, but when Express looks for a file like example.css, it first checks the /static directory. If it doesn ...

Choosing a Radio Button with a Labeled Option

I'm experimenting with a method to style radio buttons by concealing them and inserting an alternative image as the background of the corresponding label (similar to this technique). In my test, I attempted to apply CSS to the radio button label: inp ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...

Transferring an MSAL token to the backend with the help of Axios

I encountered an issue while attempting to send the user ID, which was previously decoded from a JWT token along with user input data. The problem arises when I try to send the data and receive an exception in the backend indicating that the request array ...