How to Align Items Horizontally in React Material UI Grid for Containers of Varying Item Counts

I've been utilizing the React Material UI Grid System to arrange my elements on the page, which utilizes flexboxes internally.

While everything is functioning properly, I'm struggling with horizontally aligning items in containers that have varying numbers of items.

In this example, there are 2 container items each with a width of 6. The first container includes items x1 and x2, while the second container contains y1, y2, and y3. The current arrangement looks somewhat odd; my goal is to have x1 aligned horizontally with y1, and likewise for x2 and y2.

The reason for placing x1, x2 in the first container and y1, y2, y3 in the second container is their semantic relationship. This allows me to assign different values for xs, sm, md, lg, xl to the outer container so they maintain order after breakpoint adjustments.

If I were to simply place them in 3 rows with 2 columns each, they would appear in the sequence x1, y1, x2, y2, ... which is not ideal.

Thus, my question is: how can I achieve horizontal alignment?

Edit:

This is the current appearance:

https://i.stack.imgur.com/0ZyYC.png

This is the desired look:

https://i.stack.imgur.com/Gr8h5.png

Answer №1

To achieve this desired outcome, we need to include additional props within the <Grid> component.

  1. The prop
    alignItems="flex-start"
    ensures that grid items align to the top and then cascade downwards.
  2. By using the direction="column" prop, we can alter the stacking order of items within the container. This adjustment may result in changes to the size of both the container and its attached items – for instance, xs={12} may become xs={6}, and vice versa.

Here is a snippet of example code along with a link to see it in action on sandbox:

import "./styles.css";
import { Grid } from "@material-ui/core";

export default function App() {
  return (
    <div className="App">
      <Grid alignItems="flex-start" container spacing={1}>
        <Grid container direction="column" item xs={6} spacing={1}>
          <Grid item xs={12} style={{ border: "1px solid black" }}>
            x1
          </Grid>
          <Grid item xs={12} style={{ border: "1px solid black" }}>
            x2
          </Grid>
        </Grid>
        <Grid container direction="column" item xs={6} spacing={1}>
          <Grid item xs={12} style={{ border: "1px solid black" }}>
            y1
          </Grid>
          <Grid item xs={12} style={{ border: "1px solid black" }}>
            y2
          </Grid>
          <Grid item xs={12} style={{ border: "1px solid black" }}>
            y3
          </Grid>
        </Grid>
      </Grid>
    </div>
  );
}

Click here to view the code implementation on sandbox

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

In JavaScript, creating a new array of objects by comparing two arrays of nested objects and selecting only the ones with different values

I've been struggling to make this work correctly. I have two arrays containing nested objects, arr1 and arr2. let arr1 =[{ id: 1, rideS: [ { id: 12, station: { id: 23, street: "A ...

html2canvas is unable to capture images containing captcha

Below are the HTML codes: <div id="divPage"> div_Page <br/> <img id="captchaimglogin" src="https://www.emirates.com/account/english/login/login.aspx?cptLogin_captcha=86e2a65e-f170-43b6-9c87-41787ff64a35&t=88d296b19e5e8000&mode=ss ...

Guide on routing error 500 globally to a specific page with React-Redux

Currently, I am utilizing the react-redux starter found at this link. I am seeking guidance on how to redirect all API 500 errors to a specific page. Can someone assist me with this? ...

Unusual hue in the backdrop of a daisyui modal

https://i.stack.imgur.com/fLQdY.png I have tried various methods, but I am unable to get rid of the strange color in the background of the Modal. Just for reference, I am using Tailwind CSS with Daisy UI on Next.JS. <> <button className='btn ...

What's the Best Way to Perform Testing on an MUI ToggleButtonGroup using a UserEvent?

Currently, I am implementing the MUI ToggleButtonGroup component in the following manner: <ToggleButtonGroup color="primary" value={mode} exclusive onChange={changeHandler} fullWidth className=&q ...

Buttons to maximize, minimize, and close individual sections on a webpage

I am fairly new to front end development and I must say, I am absolutely enjoying every bit of it. Here is a little challenge that came my way. It may seem simple to some but it got me thinking. I have three sections on the right side of my website. I wa ...

Using React Typescript to Assign Custom Types to Material UI TextField MenuItem Values

I encountered a type conflict in my code, unsure whether a simple casting solution exists or if there is a more fundamental issue at play. import React from "react"; import TextField from "@mui/material/TextField"; import MenuItem from ...

Trigger the React useEffect only when the inputed string matches the previous one

Currently, I am in the process of creating my own custom useFetch hook. export const useFetch = <T extends unknown>( url: string, options?: RequestInit ) => { const [loading, setLoading] = useState(false); const [error, setError] = ...

Enter your phone number in the designated field

I am looking to receive mobile numbers from various countries as input. I attempted to achieve this using the following code: <input type="tel" minlength="8" maxlength="10" name="Number" id="Number" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}" class="form-co ...

Ways to focus on a specific div using JavaScript

I am attempting to create a 'snow' effect on the background of a particular div with a red border. Here is the code, but you can also view it here: <!-- language: lang-js --> var width = getWidth(); var height = getH ...

Hover over me to see the CSS animation translate upwards until it reaches a specific point

I am new to CSS animation and I am trying to create a circle that moves from one end to the other on hover. However, I am facing an issue where the circle goes off-screen when the browser size is changed. How can I make it stop at a certain point within th ...

Making Bootstrap div stretch vertically with absolutely positioned content

Is there a way to make the middle div expand vertically on screen sizes smaller than 1000px without causing the text to flow under the image in the third div? Even clearing floats doesn't seem to solve the issue. This code is based on Bootstrap 4.4. ...

Turn off webpage caching in HTML5

I am looking for a way to disable the browser cache using HTML5. While I came across this helpful post (How to control web page caching, across all browsers?), it only provides information for HTML4 or other languages. In my web application, I utilize Ja ...

Changing the Title of UI Tabs

I am facing an issue with setting the title in tabs, as the title is appearing behind the background. If I set background: transparent; in the #tabss .ui-tabs-nav class, then my title shows up properly. Otherwise, it gets displayed behind the background. ...

Leverage environment variables in React JS to define distinct API URLs for production and development environments

For my React app, I started with create-react-app as the boilerplate. To make a request to my local server, I'm using fetch. fetch("http://localhost:3000/users") .then(function(res){ return res.json() }) .then(function(res){ return res.data }) ...

Difficulty Intercepting Browser's Back Button Press on Next.js Success Page

Currently, I am developing a Next.js application that includes a success page for users who have completed a payment transaction. My goal is to prevent users from navigating back to the payment page by intercepting the back button press and redirecting the ...

Choose a single dynamic image from a collection of multiple images

In the process of developing a Shopping cart website, I encountered an issue regarding allowing users to upload multiple images of a single product. Using jQuery, I successfully cloned the file input section to enable uploading additional images of the sam ...

Body section CSS selector

Can a CSS selector be included within the body section of an HTML document? Here's an example of my code (although it is not functioning as expected): <html> <head> </head> <body> <div style= "a[target=_blank] {backgroun ...

What is the best way to access a DOM node within a withStyle component?

Currently, I am involved in a react project where my team and I are utilizing Material UI. I encountered a situation where I needed to access the DOM node of another component that was wrapped by a HOC. To achieve this, I attempted using ref in React but o ...

Environment variables in Node process are uninitialized

I'm currently in the process of developing my first Express application, which requires interaction with an API using a secure API key. To ensure the security of this key and any future environment variables, I have decided to store them in a .env fil ...