Reordering the stacking order of Grid Items in material-ui

I'm facing an issue with the stacking order of grid items when the browser shrinks.

On a regular desktop screen (lg):

---------------------------------------------
|   col 1     |         col 2       | col 3 |
---------------------------------------------

However, upon shrinking the browser, the layout looks like this:

-------------------------
|     col 1             |
-------------------------
-------------------------
|     col 2             |
-------------------------
-------------------------
|     col 3             |
-------------------------

Is it possible to achieve the following arrangement on a mobile screen using material ui Grid layout:

-------------------------
|     col 1             |
-------------------------
-------------------------
|     col 3             |
-------------------------
-------------------------
|     col 2             |
-------------------------

I've come across articles discussing changing the order of CSS grids for similar issues, but I'm wondering how to implement this using material-ui Grid layout.

https://codesandbox.io/s/l56nr7o6p9

Answer №1

Update: I have edited the response to accommodate MUI Core v5

    <Grid container spacing={16} justify="flex-start">
      <Grid item xs={12} sm={6} md={4} lg={4}>
        <Paper>
          <h1>{1}</h1>
        </Paper>
      </Grid>
      <Grid item xs={12} sm={6} md={4} lg={4} order={{ xs: 3, sm: 2 }}>
        <Paper>
          <h1>{2}</h1>
        </Paper>
      </Grid>
      <Grid item xs={12} sm={6} md={4} lg={4} order={{ xs: 2, sm: 3 }}>
        <Paper>
          <h1>{3}</h1>
        </Paper>
      </Grid>
    </Grid>

https://codesandbox.io/s/xvv7o07614?file=/src/GridStacking.js

Answer №2

Building on Olivier's insights, Material-UI relies heavily on the CSS flexbox layout for its implementation. The documentation explains that a flex container is generated by an element with a computed display of flex or inline-flex. Children of a flex container are referred to as flex items and are arranged using the flex layout model.

In simpler terms, Grid items are considered flex items, and the Grid Container functions as a flexbox container. This allows us to manipulate the order of Grid items relative to each other when the Box or Grid Container resizes. To achieve this, apply the following style to the grid item:

  itemStyle: {
    order: ${Desired_order_before_Shrinking},

    [theme.breakpoints.up(`${DesiredScreenSize}`)]: {
      order: ${Desired_order_after_Shrinking},
    },
 
  }

To implement the above style, use

<Grid item xs={12} md={6} className={this.props.classes.itemStyle}>
. This will rearrange the items accordingly. Hopefully, this clarifies any confusion surrounding the topic.

UPDATE: With Material UI V5, thanks to @Adam Cooper's contribution below, you can reorder items as shown in the example below:

<Grid container spacing={2}>
  <Grid item md={12} lg={4} order={{ md: 1, lg: 1 }}>col 1</Grid>
  <Grid item md={12} lg={4} order={{ md: 3, lg: 2 }}>col 2</Grid>
  <Grid item md={12} lg={4} order={{ md: 2, lg: 3 }}>col 3</Grid>
</Grid>

Answer №3

Utilizing material-ui v5 allows for a more sophisticated approach by incorporating the order prop alongside the newly implemented responsive style system:

<Grid container spacing={2}>
  <Grid item md={12} lg={4} order={{ md: 1, lg: 1 }}>column 1</Grid>
  <Grid item md={12} lg={4} order={{ md: 3, lg: 2 }}>column 2</Grid>
  <Grid item md={12} lg={4} order={{ md: 2, lg: 3 }}>column 3</Grid>
</Grid>

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

I am looking to establish a secure path specifically designated for an administrative role

How can I securely pass a token from the backend to the frontend in order to protect routes? Currently, my tech stack consists of Symfony 5.4 and React 18.16. I am working on establishing an admin role and securing that specific route. Although I can view ...

How can we prevent the HTML escaping of text children in React.createElement?

Let's examine the call to React.createElement: React.createElement('span', null, null, ['&gt;&lt;',]) When executing this code, React will escape the characters &gt; and &lt;. Is there a method to prevent these sp ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

Customizing the appearance of a JavaScript countdown timer's output on an individual basis

I am currently working on customizing the appearance of a JavaScript date counter. My goal is to style the days, hours, minutes, and seconds individually. Ideally, I want each unit to be right-aligned within its own div, with specific left and top absolute ...

Creating click event handler functions using TypeScript

I encountered an issue when trying to set up an event listener for clicks. The error message I received was that classList does not exist on type EventTarget. class UIModal extends React.Component<Props> { handleClick = (e: Event) => { ...

Express server and create-react-app build facing issues with Glyphicons and fonts functionality

Encountering an issue in the browser console: Failed to decode downloaded font "localhost:5000/static/media/fontname.@#$.woff" OTS parsing error: invalid version tag Came across some suggested solutions like adding a homepage:"./" to package.json. However ...

Tips for adjusting UI size in CSS based on viewport dimensions and accommodating image content

The elements E1, E2, E3, E4 are all part of the user interface (UI) and are intended to have a hover effect. Additionally, there is a background image included in the design. Currently, this is the progress made on the project: <div class="bg"> ...

Ensure that CSS is integrated correctly

I have a main Django template that incorporates another template for the navigation bar. I currently have separate CSS files for both the main page and the navbar. My query is: what is the correct method to include the CSS from the navbar in the main p ...

Ways to insert additional panels prior to and after a selected panel

A button is provided in the report designer detail band that, when clicked, should add new panels immediately before and after the detail panel. $parentpanel = $this.parents(".designer-panel:first"); This code snippet is used to locate the parent panel u ...

Is the misalignment due to a floating point error?

Attempted to create a 3-column layout without responsiveness, but encountered an odd alignment issue. http://jsfiddle.net/z5mgqk6s/ #DIV_1 { box-sizing: border-box; color: rgb(255, 255, 255); height: 83.2px; text-align: center; widt ...

Ways to classify the prop type of a functional component by specifying the different types of props for the FC

I have created two functional components that require different prop types. export interface OrderImageProps { orders: ICartItem[] } const OrderImage: React.FC<OrderImageProps> = (props: OrderImageProps) => { return ( <div> ...

Encountered an unusual IP address while attempting to start yarn - EADDRNOTAVAIL

Recently, I installed OpenSUSE on my laptop and decided to try out a new React application. However, when I ran the commands from the create-react-app site: npx create-react-app my-app cd my-app yarn start I encountered an issue in my terminal with the f ...

What is the best way to retrieve all string constants from HTML or JSX code?

UPDATE: I recently developed my own babel plugin CLI tool named i18nize-react :D I am currently in the process of translating an existing react application from English to another language. The string constants in the JSX are all hardcoded. Is there a sim ...

What is the process for determining the area of the section?

Take a look at this page as an example - scrolling down on responsive devices reveals related navigation areas which I aim to change with scrollspy (affix fixed navigation). Having a bootstrap navbar, when on the corresponding section of the navbar while u ...

Tips for showing a DialogBox when a blur event occurs and avoiding the re-firing of onBlur when using the DialogBox

Using React and Material UI: In the code snippet provided below, there is a table with TextFields in one of its columns. When a TextField triggers an onBlur/focusOut event, it calls the validateItem() method that sends a server request to validate the ite ...

Is the Mini Cart button in Woocommerce not aligned properly?

My website was functioning perfectly until yesterday. However, after updating some plugins, the Mini Cart dropdown button started to display in a weird and misaligned manner. https://i.sstatic.net/SsZee.jpg Prior to the plugin updates, the button had the ...

Is there a way to move the submit form button to the next line using CSS?

I am having trouble centering the submit button below two input fields in a simple React form. Can anyone offer assistance with this? HTML .SearchBar-fields { display: flex; justify-content: center; margin-bottom: 2.88rem; flex-direction: row; ...

error: cannot locate firebase object

I'm currently working on building a chat application using React and Firebase. However, upon adding the Firebase database, I encountered an error. Firebase Storage: Object 'mandy' does not exist. (storage/object-not-found) FirebaseError: Fi ...

Switch the Material UI text field color from black to a crisp white hue

Hello, I have been trying to figure this out but couldn't find the solution anywhere. I simply want the following fields to be white: https://i.sstatic.net/mdhVU.png Specifically, I am looking to change the default labels and border color to white. ...

React, ShoppingCart, and browser storage

I am experiencing two issues with my shopping cart. The first problem is that when I increase or decrease the quantity of an item in the cart, it moves to the bottom of the item list. Additionally, I have been attempting to save the items, quantities, and ...